Reputation: 158
Why there are different results of bitwise left shift?
1 << 32; # 1
1 << 31 << 1; # 0
Upvotes: 1
Views: 49
Reputation: 114529
The reason is that the shift count is considered modulo 32.
This itself happens because (my guess) this is how most common hardware for desktops/laptops works today (x86).
This itself happens because.... well, just because.
These shift limitations are indeed in some cases annoying... for example it would have been better in my opionion to have just one shift operator, working in both directions depending on the sign of the count (like ASH
works for Common Lisp).
Upvotes: 0
Reputation: 385194
JavaScript defines a left-shift by 32 to do nothing, presumably because it smacks up against the 32-bit boundary. You cannot actually shift anything more than 31 bits across.
Your approach of first shifting 31 bits, then a final bit, works around JavaScript thinking that shifting so much doesn't make sense. Indeed, it's pointless to execute those calculations when you could just write = 0
in the first place.
Upvotes: 0
Reputation: 254944
That's because of
Let
shiftCount
be the result of masking out all but the least significant 5 bits ofrnum
, that is, computernum & 0x1F
.
of how the <<
operation is defined. See http://www.ecma-international.org/ecma-262/6.0/#sec-left-shift-operator-runtime-semantics-evaluation
So according to it - 32 & 0x1F
equals 0
So 1 << 32
equals to 1 << 0
so is basically no op.
Whereas 2 consecutive shifts by 31 and 1 literally perform calculations
Upvotes: 1