Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in JavaScript expression 255 << 24 is a negative number?

When I run this code here:

console.log(255<<24==0xff000000)

I get a false instead of true. Why is that?

like image 468
Adler Avatar asked Mar 22 '23 22:03

Adler


1 Answers

Because JavaScript numbers are IEEE-754 double-precision floating point, not 32-bit integers. So 0xff000000 is a large positive number (decimal 4,278,190,080), not a negative number as it would be if that were a signed 32-bit integer.

When you do <<, the number being shifted (255 in your case) is temporarily converted to a signed 32-bit integer for the purposes of doing the bit shift:

00000000000000000000000011111111
^\                             /
| \----- significant bits ----/
+------- sign bit

When we shift that 24 places left, a 1 bit ends up in the sign bit:

11111111000000000000000000000000
^\                             /
| \----- significant bits ----/
+------- sign bit

...and so the result ends up being negative, and gets turned back into a negative IEEE-754 number (-16,777,216 decimal). -16,777,216 is not equal to 4,278,190,080.

(The range of IEEE-754 double-precision floats is larger than the range of 32-bit signed integers. I'm not quite sure why I feel that's relevant, but I do, so I guess I'll leave it in the answer...)

like image 95
T.J. Crowder Avatar answered Apr 05 '23 19:04

T.J. Crowder