Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

32 bit unsigned JavaScript bitwise operation is one short

Why does

((255<<24)|(255<<16)|(255<<8)|255)>>>0

equals 4294967295 when

Math.pow(256,4)

equals 4294967296?

Notice that the bitwise operation is one short. Why is this?!

like image 351
talentedmrjones Avatar asked Sep 12 '11 20:09

talentedmrjones


2 Answers

Because zero takes up a binary value.

4294967296 is the number of "slots" that 32 bits gives you, 4294967295 is the decimal number occupying highest slot.

like image 146
Barend Avatar answered Sep 23 '22 07:09

Barend


Because the first one is 2^32-1, and the second one is 2^32? You know that with the first "statement" you are setting to 1 the first 32 bits of a value, right?

In 32 bits, the first bit is "valued" 1, the second 2, the third 4... The 32th 2147483648. Their sum is 4294967295 :-)

Let's make an example with 8 bits.

Math.pow(256,1) == 256

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255.
like image 26
xanatos Avatar answered Sep 20 '22 07:09

xanatos