如果在 javascript 中所有数字都是 64 位浮点数并且没有 64 位整数,那么您不能期望以该精度定义 a 和 b(或 fd 和 filtermask),而不会出现舍入错误。
尝试定义一个封装 64 位整数类型的对象。
作为示例,您可以查看 Mozilla MDN 制作的 js-ctype 实现:
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Int64
特别是
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Working_with_data#64-bit_integers
他们的 Int64 和 UInt64 对象不提供任何执行算术的方法,但您可以提取高 32 位和低 32 位部分并对它们进行数学运算,然后将它们重新组合在一起。
一个简单的代码示例,改为使用类型化数组:
bitMask = function(high = 0x0,low = 0x0) {
this.bm = new Uint32Array(2);
if (arguments.length === 0 ) {
this.bm[0] = 0x0;
this.bm[1] = 0x0;
} else if (arguments.length === 2 && typeof arguments[0] === "number" && typeof arguments[1] === "number") {
this.bm[0] = arguments[1];
this.bm[1] = arguments[0];
}
this.bwAND = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] & filter.bm[0];
result.bm[1] = this.bm[1] & filter.bm[1];
return result;
}
this.bwOR = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] | filter.bm[0];
result.bm[1] = this.bm[1] | filter.bm[1];
return result;
}
this.bwXOR = function(filter) {
result = new bitMask();
result.bm[0] = this.bm[0] ^ filter.bm[0];
result.bm[1] = this.bm[1] ^ filter.bm[1];
return result;
}
this.bwNOT = function() {
result = new bitMask();
result.bm[0] = ~this.bm[0];
result.bm[1] = ~this.bm[1];
return result;
}
this.bwEQUALS = function(b){
return (this.bm[0] == b.bm[0]) && (this.bm[1] == b.bm[1]);
}
this.toString = function() {
var zeroes = "00000000000000000000000000000000";
var strH = this.bm[1].toString(2);
var zerH = zeroes.substr(0,32-strH.length);
var strL = this.bm[0].toString(2);
var zerL = zeroes.substr(0,32-strL.length);
return zerH + strH + zerL + strL;
}
}
你可以像这样使用它:
var a = new bitMask(0x0FEDCBA9,0xFF00FF00);
var b = new bitMask(0x12345678,0x0000FFFF);
var c = b.bwAND(a);
var d = b.bwOR(a);
var e = b.bwXOR(a);
var f = b.bwNOT();
var g = b.bwEQUALS(a);
结果:
a = 0000111111101101110010111010100111111111000000001111111100000000
b = 0001001000110100010101100111100000000000000000001111111111111111
a & b = 0000001000100100010000100010100000000000000000001111111100000000
a | b = 0001111111111101110111111111100111111111000000001111111111111111
a ^ b = 0001110111011001100111011101000111111111000000000000000011111111
~b = 1110110111001011101010011000011111111111111111110000000000000000
(a == b)? = false