# bit shifting

jeff mutonho

Ranch Hand

Posts: 271

B. Du Bois

Greenhorn

Posts: 4

posted 12 years ago

- 0

Suppose you want to shift int X to the right over B bits, then you would write simply: X >> B. In that case only the 5 lowest-order bits of B are used, which basically means that you can shift over maximum 32 bits. When you want to shift a long, the 6 lowest-order bits of B are used, so you can shift over maximum 64 bits.

If you try to shift over more than 32 (long: 64) bits, the highest-order bits are ignored, this is the same as doing modulo 32 (long: 64). So shifting over 35 bits results in the same as shifting over 3 bits.

Some examples:

int X;

X >> 5; // shifts 5 bits to the right

X >> 32; // shifts 0 bits to the right, does nothing

X >> 33; // shifts 1 bit to the right

If you try to shift over more than 32 (long: 64) bits, the highest-order bits are ignored, this is the same as doing modulo 32 (long: 64). So shifting over 35 bits results in the same as shifting over 3 bits.

Some examples:

int X;

X >> 5; // shifts 5 bits to the right

X >> 32; // shifts 0 bits to the right, does nothing

X >> 33; // shifts 1 bit to the right

Ray Stojonic

Ranch Hand

Posts: 326

posted 12 years ago

- 0

An int is 32 bits, so the largest sensible shift would be 31 positions. 31 happens to be the largest number representable by 5 bits.

(working with bytes to keep size reasonable)

int i = -2;

an int is created and initialized to -2, in binary:

-2 = 1111 1110

i >>>= -1;

right-shift, zero fill, by -1. we know -1 = 1111 1111, but, as we're

working with ints, we're only interested in the 'low-order 5 bits'.

behind the scenes, a mask of 31 is 'anded' to our shift amount:

1111 1111

&0001 1111

=0001 1111 == 31, so our -1 right shift is really a 31 right shift.

-2 >>>= 31 == 0000 0001 == 1

another example

int i = 123 << 32;

123 == 0111 1011

32 == 0010 0000

0010 0000

&0001 1111

=0000 0000

123 << 0 == 0111 1011 == 123

Hopefully, that was clear enough. For longs, its the same idea but with 64 bits in the long and 6 bits in the shift.

hth

(working with bytes to keep size reasonable)

int i = -2;

an int is created and initialized to -2, in binary:

-2 = 1111 1110

i >>>= -1;

right-shift, zero fill, by -1. we know -1 = 1111 1111, but, as we're

working with ints, we're only interested in the 'low-order 5 bits'.

behind the scenes, a mask of 31 is 'anded' to our shift amount:

1111 1111

&0001 1111

=0001 1111 == 31, so our -1 right shift is really a 31 right shift.

-2 >>>= 31 == 0000 0001 == 1

another example

int i = 123 << 32;

123 == 0111 1011

32 == 0010 0000

0010 0000

&0001 1111

=0000 0000

123 << 0 == 0111 1011 == 123

Hopefully, that was clear enough. For longs, its the same idea but with 64 bits in the long and 6 bits in the shift.

hth

It is sorta covered in the JavaRanch Style Guide. |