James Monger
James Monger

Reputation: 10665

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

Upvotes: 1

Views: 272

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

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.

(0xFFFF << 16) >>> 0 == 0xFFFF0000

Upvotes: 3

Related Questions