Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# shifting bits of -1

Kevin Tysen
Ranch Hand
Posts: 255
I have been experimenting with shifting bits around. For example, if I do

-1 << 24

I get a number, when written out in bits is

11111111000000000000000000000000

However, I did this

-1 << 32

and expected

00000000000000000000000000000000

However, I got this:

11111111111111111111111111111111

Why?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15571
46
That's because when you shift an int 32 times, it will really be shifted 0 times instead of 32 times.

Section 15.19 of the Java Language Specification explains this:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

So, in the case of an int, only the lowest five bits of the shift distance are used. The lowest five bits of the number 32 are all 0, so the real shift distance is 0 (32 & 0x1f = 0).