简体   繁体   English

获取两个(二进制)数字之间不同的位数

[英]Get the bit number that differs between two (binary) numbers

I have two numbers (binary or not, does not play any role) which differ in just one bit, eg (pseudocode) 我有两个数字(二进制​​或不二进制,不起任何作用),只有一位不同,例如(伪代码)

a = 11111111
b = 11011111

I want a simple python function that returns the bit position that differs ('5' in the given example, when seen from right to left). 我想要一个简单的python函数,它返回不同的位位置(给定示例中的“5”,从右到左)。 My solution would be (python) 我的解决方案是(python)

math.log(abs(a-b))/math.log(2)

but I wonder if there is a more elegant way to do this (without using floats etc.). 但我想知道是否有更优雅的方法来做到这一点(不使用花车等)。

Thanks Alex 谢谢Alex

You could use the binary exclusive: 您可以使用二进制独占:

a = 0b11111111
b = 0b11011111

diff = a^b  # 0b100000
diff.bit_length()-1 # 5 (the first position (backwards) which differs, 0 if a==b )

Without using bitwise operations you could do something like this: 不使用按位运算,您可以执行以下操作:

In [1]: def difbit(a, b):
   ...:     if a == b: return None
   ...:     i = 0
   ...:     while a%2 == b%2:
   ...:         i += 1
   ...:         a //= 2
   ...:         b //= 2
   ...:     return i
   ...: 

In [2]: difbit(0b11111111, 0b11011111)
Out[2]: 5

unless i am missing something... 除非我遗漏了什么......

this should work: 这应该工作:

>>> def find_bit(a,b):
    a = a[::-1]
    b = b[::-1]
    for i in xrange(len(a)):
        if a[i] != b[i]:
            return i
    return None

>>> a = "11111111"
>>> b = "11011111"
>>> find_bit(a,b)
5

maybe not so elegant, but its easy to understand, and it gets the job done. 也许不是那么优雅,但它易于理解,并且它完成了工作。

Using (a^b).bit_length()-1 is perfect for numbers which have only one difference bit. 使用(a^b).bit_length()-1对于只有一个差异位的数字是完美的。 EX: EX:

a = 1000000
b = 1000001
(a^b).bit_length()-1
Output: 0

But for numbers which have multiple difference bits, it gives the index of left most difference bit. 但是对于具有多个差异位的数字,它给出了最左边的差分位的索引。 EX: EX:

a = 111111111111111111111111111111
b = 111111110111011111111111111111
c = a^b   # 1000100000000000000000
c.bit_length()-1
Output: 21  # Instead of 17. 21 is the left most difference bit

So to solve this problem we need to isolate the right most set bit and then get its index. 因此,要解决此问题,我们需要隔离最右边的设置位,然后获取其索引。 Thus, using ((a^b) & (-(a^b))).bit_length()-1 works best for all inputs: 因此,使用((a^b) & (-(a^b))).bit_length()-1最适合所有输入:

c = (a^b) & (-(a^b))   # 100000000000000000 - Isolates the rightmost set bit
c.bit_length()-1
Output: 17
(a^b) & (-(a^b))).bit_length()-1
Output: 17

Learn about isolating right most set bit from here 了解从这里隔离最右边的设置位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM