繁体   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