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

2
  • can you share with us your javascript code that does the & operation? Commented Apr 4, 2013 at 7:29
  • 2
    console.log(4294901760 & 4294967040); this is complete code :) Commented Apr 4, 2013 at 7:32

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.