代码之家  ›  专栏  ›  技术社区  ›  pritesh

如何在javascript中查找两个数字之间的位差

  •  7
  • pritesh  · 技术社区  · 8 年前

    假设我有2个数字,例如1和2。它们的二进制表示是“01”和“10”,所以它们的位差是2。对于数字5和7,二进制表示是“101”和“111”,所以位差是1。当然,我可以将这两个数字都转换成二进制,然后循环查找差,但是有更简单的方法吗??

    3 回复  |  直到 8 年前
        1
  •  1
  •   CertainPerformance    8 年前

    可以使用位异或( ^ )要识别位不同的位置,请将结果转换为字符串,然后计算 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));
        2
  •  2
  •   TylerY86    8 年前

    啊,根据certainperformance的答案,字符串op是一种简单的方法,但这里有一个纯粹的位解决方案。

    这是一个扁平的循环,处理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

    如果您需要任意大的值,请告诉我…

    它需要使用类型化数组、上述函数和循环。

        3
  •  0
  •   GorvGoyl    7 年前

    1)XOR两个数字: 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))); 
    }