16-bit value becomes negative when bit shifting in JavaScript

Multi tool use
16-bit value becomes negative when bit shifting in JavaScript
I am seeing some odd behaviour when I try to bit shift a 16-bit value
0xF << 4 == 0xF0 // true
0xFF << 8 == 0xFF00 // true
0xFFF << 12 == 0xFFF000 // true
0xFFFF << 16 == 0xFFFF0000 // false
The reason the last one is true is that 0xFFFF << 16
actually gives the value -65536
. Why is this happening when 0xFFFF0000
is a valid number in JavaScript
0xFFFF << 16
-65536
0xFFFF0000
1 Answer
1
Because Javascript uses signed 32-bit integers numbers for bitwise operations.
That means, the numbers can be negative.
To have your desired output, you have to remove the sign with >>> 0
.
>>> 0
(0xFFFF << 16) >>> 0 == 0xFFFF0000
(0xFFFF << 16) >>> 0
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks. I can get the output I want with
(0xFFFF << 16) >>> 0
– James Monger
Jun 30 at 8:50