Bitwise & in javascript not returning the expected result
Asked Answered
H

3

6

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

Hypertonic answered 4/4, 2013 at 7:26 Comment(2)
can you share with us your javascript code that does the & operation?Lemcke
console.log(4294901760 & 4294967040); this is complete code :)Hypertonic
L
7
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?

Lemcke answered 4/4, 2013 at 7:36 Comment(0)
H
1

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
Holmium answered 4/4, 2013 at 7:39 Comment(0)
N
0

Check this custom implementation of AND bitwise 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

Nonessential answered 13/3, 2014 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.