簡體   English   中英

如何在JavaScript中找到兩個數字之間的位差

[英]How to find Bit Difference between two numbers in Javascript

假設我有2個數字,例如1和2。它們的二進制表示形式是'01'和'10',所以它們的位差是2。對於數字5和7,二進制表示形式是'101'和'111',所以位差是1當然,我可以將兩個數字都轉換為二進制,然后循環查找其差值,但是有沒有更簡單的方法呢?

嗯,根據SomePerformance的答案,字符串操作是實現此目的的簡便方法,但這只是一個按位的解決方案。

這是一個扁平的循環,用於處理JavaScript有限的32位int支持。

 // implementation of the "bit population count" operation for 32-bit ints function popcount(u) { // while I'm at it, why not break old IE support :) if ( !Number.isInteger(u) ) throw new Error('Does not actually work with non-integer types.'); // remove the above check for old IE support u = (u & 0x55555555) + ((u >> 1) & 0x55555555); u = (u & 0x33333333) + ((u >> 2) & 0x33333333); u = (u & 0x0f0f0f0f) + ((u >> 4) & 0x0f0f0f0f); u = (u & 0x00ff00ff) + ((u >> 8) & 0x00ff00ff); u = (u & 0x0000ffff) + ((u >>16) & 0x0000ffff); return u; } // select all bits different, count bits function diffcount(a, b) { return popcount( a ^ b ); } // powers of two are single bits; 128 is common, bits for 16, 32, and 8 are counted. // 128+16 = 144, 128+32+8 = 168 console.log(diffcount(144,168)); // = 3 // -1 is 4294967295 (all bits set) unsigned console.log(diffcount(-1,1)); // = 31 // arbitrary example console.log(diffcount(27285120,31231992)); // = 14 

如果您需要任意大的值,請告訴我...

它需要使用類型化數組,上述函數和循環。

您可以使用按位XOR( ^ )來識別位不同的位置,將結果轉換為字符串,然后計算字符串中出現1的次數:

 const bitDiffCount = (a, b) => { const bitStr = ((a ^ b) >>> 0).toString(2); return bitStr.split('1').length - 1; }; console.log(bitDiffCount(5, 7)); console.log(bitDiffCount(1, 2)); console.log(bitDiffCount(16, 16)); console.log(bitDiffCount(16, 17)); console.log(bitDiffCount(16, 18)); console.log(bitDiffCount(16, 19)); 

1)將兩個數字異或: x = a^b

2)檢查XOR結果是否為2的冪。如果為2的冪,則僅存在1位差。 (x && (!(x & (x - 1))))應該為1

bool differAtOneBitPos(unsigned int a, 
                       unsigned int b) 
{ 
    return isPowerOfTwo(a ^ b); 
}

bool isPowerOfTwo(unsigned int x) 
{ 
    return x && (!(x & (x - 1))); 
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM