Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird result of Java Integer left shift

I'm a little confused now by java left shift operation,

1<<31 =  0x80000000  --> this I can understand

But

1<<32 =  1       Why is this?
1<<33 =  2       

Looks like more shifting values, modulus 32 of the value is taken.

Thanks everybody for the replying and giving the quote from JLS.

I just want to know more. Any idea of the reason why it's designed in this way? Or is it just some convention? Apparently C doesn't have this quirk?

Thanks to @paxdiablo. Looks like C declares this behaviour undefined.

I have some personal assumption here:

ARM architecture Reference Manual A7.1.38

Syntax LSL Rd, Rm, #immed_5

where:

Rd Is the register that stores the result of the operation.

Rm Is the register containing the value to be shifted.

immed_5 Specifies the shift amount, in the range 0 to 31.

On instruction level, the immeidate immed_5 takes only 5 bits to avoid meaningless operations so as to save some instruction space. I guess high level languages just unitize this convention to avoid meaningless effort when compile to instructions.

like image 670
Bill Randerson Avatar asked Dec 10 '15 04:12

Bill Randerson


People also ask

What happens when you left shift a number?

The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2. Use the left shift for fast multiplication or to pack a group of numbers together into one larger number.

What happens when you bit shift an integer?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.

What does Left Shift do Java?

The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by << . As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.


1 Answers

As per the Java Language Specification 15.19. Shift Operators (slightly paraphrased):

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 & with the mask value 0x1f ,or 0b11111. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

That means that (for example) 33, being the 6-bit binary 100001, is reduced to the 5-bit 00001 before being used. So x << 33 is identical to x << 1.

like image 176
paxdiablo Avatar answered Sep 28 '22 03:09

paxdiablo