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.
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.
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.
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.
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 value0x1f
,or0b11111
. The shift distance actually used is therefore always in the range0
to31
, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With