Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise & in javascript not returning the expected result

I am working on BitWise AND operator in javascript.

I have two 32 bit nunber

4294901760 (11111111 11111111 00000000 00000000) and

4294967040 (11111111 11111111 11111111 00000000)

when I and them bitwise 4294901760 & 4294967040 I got -65536 as a result although the result should be 4294901760.

Can any one please guide me am I missing something? Or what is the correct way to do it. Thanks

like image 712
user2243651 Avatar asked Apr 04 '13 07:04

user2243651


2 Answers

console.log((4294901760 & 4294967040) >>> 0);

Append >>> 0 to have it interpret your operation as unsigned.

Fiddle:
http://jsfiddle.net/JamZw/

More info:
Bitwise operations on 32-bit unsigned ints?

like image 143
Jace Avatar answered Sep 26 '22 01:09

Jace


Operands of bitwise operations in javascript are converted to signed 32 bit integers. Unsigned 4294901760 has same binary representation as signed -65536. You can use >>> 0 to convert result of & to unsigned, eg:

(4294901760 & 4294967040) >>> 0
like image 32
pfyod Avatar answered Sep 23 '22 01:09

pfyod