Javascript int are actually float. When '&' bit-wise AND is used, the value is converted to integer and operated on. It's 32 bits only, and is signed by default. So for big int longer than this, there is no way to do bit-wise AND.
Here is a solution: first convert the input integer string (a string, not a int) into binary format, then do a bit by bit comparison. Code is below.
function BIGINT_AND(a, b) {
a = toBinary(a);
b = toBinary(b);
for (var i = a.length - 1, j = b.length - 1; i >= 0 && j >= 0; -- i, -- j) {
if (a[i] == 1 && b[j] == 1) return 1;
}
return 0;
}
// convert from decimal format to binary format
function toBinary(decNum){
return parseInt(decNum,10).toString(2);
}
Wednesday, January 15, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment