aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes bit shifting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "bit shifting" Watch "bit shifting" New topic
Author

bit shifting

jeff mutonho
Ranch Hand

Joined: Apr 30, 2003
Posts: 271
In their study guide , Roberts ,Heller and Ernest say "shifts of ints use only the low-order 5 bits ,and shifts of longs use only the low-order 6bits , of the right operand".What does this mean?Example?
jeff
B. Du Bois
Greenhorn

Joined: Dec 22, 2003
Posts: 4
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
Ray Stojonic
Ranch Hand

Joined: Aug 08, 2003
Posts: 326
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
jeff mutonho
Ranch Hand

Joined: Apr 30, 2003
Posts: 271
Thanx guys.Making sense now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: bit shifting