javascript integers can go 2^53, yet bit operations go 2^32. need perform bit operations on numbers between 2^32 , 2^53, have write substitute functions bit operations:
here's have far:
function lshift(num, bits) { return num * math.pow(2, bits); } function rshift(num, bits) { return math.floor(num / math.pow(2, bits)); }
is best way implement shift functions?
i need implement &
, |
. in code have &
127 , 128 i'm not sure of how so.
i don't need ~
or ^
, included in answer completeness guess.
one general remark: it seems make sense keep numbers positive avoid issues 1-complement.
for lshift function, not sure if pay off checks if shift won't overflow 32 bit, , use regular shift operation in case: it might reduce complex operations, add checks , branching...
function and(a, b) { var low = & b & 0x7fffffff; if (a <= 0x7fffffff || b <= 0x7fffffff) { return low; } var hi = rshift(a, 31) & rshift(b, 31); return low + lshift(hi, 31); } function or(a, b) { var low = (a | b) & 0x7fffffff; if (a <= 0x7fffffff && b <= 0x7fffffff) { return low; } var hi = rshift(a, 31) | rshift(b, 31); return low + lshift(hi, 31); } function xor(a, b) { var low = (a ^ b) & 0x7fffffff; if (a <= 0x7fffffff && b <= 0x7fffffff) { return low; } var hi = rshift(a, 31) ^ rshift(b, 31); return low + lshift(hi, 31); } function rshift(num, bits) { return num <= 0x7fffffff ? num >> bits : math.floor(num / math.pow(2, bits)); }
edit: fixed bug in or, added xor
Comments
Post a Comment