Posts

Showing posts with the label bit-manipulation

16-bit value becomes negative when bit shifting in JavaScript

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 Thanks. I can get the output I want with (0xFFFF << 16) >>> 0 – James Monger Ju...