Translate

Monday 11 August 2014

Bitwise shifting operators in Java

Bitwise operators are used to manipulate individual bits of a variable.
In java -ve value is always stored in two's complement form.


Left shift operator (<<):- This operator is used to shift individual bits of a variable towards left by specified number of location and fills the vacant places with zero. In simple terms if we write

a = b << n;
It means a = b * (2 ^ n);

int a = 2;
a = a << 4;
it means bits of a should shift left 4 places
a = 2 = 0000 0000 0000 0000 0000 0000 0000 0010   //bits representation
now after left shifting
a = 0000 0000 0000 0000 0000 0000 0010 0000
i.e. a = 32 = 2 * (2^4)



Signed right shift operator (>>):- This operator is used to shift individual bits of a variable towards right by specified number of location and fills the vacant places with sign bit. In simple terms if we write

a = b << n;
It means a = b / (2 ^ n);

int a = 32;
a = a >> 4;
it means bits of a should shift right 4 places
a = 32 = 0000 0000 0000 0000 0000 0000 0010 0000   //bits representation
now after right shifting
a = 0000 0000 0000 0000 0000 0000 0000 0010
i.e. a = 2 = 32 / (2^4)

int a = -32
a = a >> 4;
a = -32 = 1111 1111 1111 1111 1111 1111 1110 0000
now after right shifting we will use sign bit to fill the spaces which is 1 here
a = 1111 1111 1111 1111 1111 1111 1111 1110
i.e. a = -2 = -32 / (2^4)


0 fill right shift operator (>>>):- This operator is used to shift individual bits of a variable towards right by specified number of location and fills the vacant places with 0. For +ve number both right shift operator are same.

In case of -ve number.

int a = -32
a = a >>> 4;
a = -32 = 1111 1111 1111 1111 1111 1111 1110 0000
now after right shifting we will fill vacant places by 0 here
a = 0000 1111 1111 1111 1111 1111 1111 1110

Note:- Bitwise operators can be applied to INTEGER variables only.

No comments:

Post a Comment

Total Pageviews