Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 0x80000000 >> 1 in JavaScript produce a negative value?

Doing some tests with bitwise operations / shifting with JavaScript

0x80000000 >> 1 // returns -1073741824 (-0x40000000)

I would expect that to return 0x40000000 since

0x40000000 >> 1 // returns 0x20000000
0x20000000 >> 1 // returns 0x10000000
like image 948
lostsource Avatar asked Dec 27 '12 22:12

lostsource


1 Answers

Its an arithmetic shift that's why the sign is preserved, to do a logical shift use >>>

0x80000000 >>> 1 // returns 1073741824 (0x40000000)
like image 123
Musa Avatar answered Sep 28 '22 14:09

Musa