我在JavaScript中有2个要咬和的數字.它们都长33bit
在C#中:
((4294967296 & 4294967296 )==0) is false
但使用javascript:
((4294967296 & 4294967296 )==0) is true
4294967296是((long)1)<< 32
据我了解,這是由於JavaScript在執行按位運算時会將值轉換為int32。
我该如何解決? 關於如何用其他一組數學運算替換位以及不丢失位的任何建議?
最新回復
- 5月前1 #
- 5月前2 #
這是一个有趣的函式,用於任意大的整數:
function BitwiseAndLarge(val1, val2) { var shift = 0, result = 0; var mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones) var divisor = 1 << 30; // To work with the bit mask, we need to clear bits at a time while( (val1 != 0) && (val2 != 0) ) { var rs = (mask & val1) & (mask & val2); val1 = Math.floor(val1 / divisor); // val1 >>> 30 val2 = Math.floor(val2 / divisor); // val2 >>> 30 for(var i = shift++; i--;) { rs *= divisor; // rs << 30 } result += rs; } return result; }
假定系統至少可以正確處理30位按位運算。
- 5月前3 #
Javascript中有多个BigInteger庫,但是目前没有一个提供您需要的按位運算.如果您有動力,並且確實需要该功能,則可以修改其中的一个庫並添加方法.他们已经提供了一个很好的代碼庫来處理大量代碼。
您可以在此問题中找到Javascript中BigInteger庫的列表:
巨大的整數JavaScript庫
- 5月前4 #
The simplest bit-wise AND, that works up to JavaScript's maximum number
由於內部原因,JavaScript的最大整數值為2 ^ 53(這是双精度浮點數).如果您需要更多資源,那麼可以使用好的庫来處理大整數。
2 ^ 53是9,007,199,254,740,992,或大約9,000万亿(約9万亿)。
// Works with values up to 2^53 function bitwiseAnd_53bit(value1, value2) { const maxInt32Bits = 4294967296; // 2^32 const value1_highBits = value1 / maxInt32Bits; const value1_lowBits = value1 % maxInt32Bits; const value2_highBits = value2 / maxInt32Bits; const value2_lowBits = value2 % maxInt32Bits; return (value1_highBits & value2_highBits) * maxInt32Bits + (value1_lowBits & value2_lowBits) }
您可以將每个變數分成2个32位值(例如高位字和低位字) 字),然後對這两對都进行按位運算。
下面的指令碼作為windows .js指令碼執行.您可以將wScript.Echo()替換為web的alert()。