bitwise operators - Left shifting with a negative shift count in Javascript -
a thing noticed in javascript -
a << -1
returns 0 when = even. returns -2147483648 when = odd. similarly, different values returned when -1 changed other -ve number. can explain bit operations taking place under hood ? or behavior undefined ?
thanks
edit
also shouldn't zero-fill right shift i.e. -2 >>> 1 return 7 ?
-2 = 1110. after, right shift zero-fill, should give 0111 = 7
but a = -2; console.log(a >>> 1); returns 2147483647
i wondered how landed here. i’ve done little research , figured out behavior. javascript treats operand , shift value sequences of bits rather numbers. works 32 bit integers (floats truncated) , maximum shift 32 bits. if shift number greater 32, bits shift out, resulting in zero. ensure shift less or equal 32, javascript truncates 5 least significant bits [a << (b&0x1f)] or possibly modulus method [a << (b%32)] yields same result.
with out of way, think of negative number shifting sequence of bits, not negative number (i.e. -1). in case b = -1 = 0xffffffff. since number larger 32, truncated 0xffffffff & 0x1f = 31 or 0xffffffff % 32 = 31.
so in example “a" gets shifted way least significant bit significant bit (the sign bit). therefor result of shift either 0x00000000 or (0x80000000 = -2147483648) depending on whether operand had 1 bit set (odd or even).
Comments
Post a Comment