Bitwise and in javascript does not return the expected result

I am working on a 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 their bitwise 4294901760 & 4294967040 , I got -65536 as a result, although the result should be 4294901760 .

Can someone visit me, am I missing something? Or that this is the right way to do it. Thanks

+6
source share
3 answers
 console.log((4294901760 & 4294967040) >>> 0); 

Add >>> 0 to interpret your operation as unsigned.

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

Additional Information:
Bitwise operations with 32-bit unsigned targets?

+8
source

Javascript bitwise operands are converted to signed 32-bit integers . Unsigned 4294901760 has the same binary representation as the -65536 signature. You can use >>> 0 to convert the result & to unsigned, for example:

 (4294901760 & 4294967040) >>> 0 
+1
source

Check out this custom implementation and bitwise AND operation:

 function and(a, b){ a = a.toString(2).split(''); b = b.toString(2).split(''); var length = Math.max(a.length, b.length); function padZeroes(array, size){ while(array.length <= size ){ array.unshift('0'); } } padZeroes(a, length); padZeroes(b, length); var result = []; $.each(a, function(i, v){ result.push((a[i]==b[i] && a[i]!='0')?'1':'0'); }); var r = parseInt(result.join(''), '2'); return r; } 

jsfiddle

0
source

All Articles