Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 4294967295 >> 24 == -1 in Javascript?

Tags:

javascript

I am calculating luminosity in Javascript using:

luminosity = (5036060 * backgroundColor.red + 9886846 * backgroundColor.green + 1920103 * backgroundColor.blue) >> 24;

For the case where the color is white, ie all 3 RGB values are 255, I am getting a result of -1. I tested explicitly and in Javascript the value "4294967295 >> 24" is -1.

Why?

like image 314
David Thielen Avatar asked Jan 09 '23 16:01

David Thielen


1 Answers

JavaScript does use 32-bit integers for bitwise operations. The unsigned value +4294967295 has just the same representation as -1 for signed 32-bit integers - a series of 32 1-bits. If you shift that using the signed right shift operator, it will get filled up with the sign bit, and -1 >> x always ends up with -1.

Use the unsigned right shift operator instead:

4294967295 >>> 24 // 255
like image 168
Bergi Avatar answered Jan 13 '23 20:01

Bergi