Alex Alex - 1 month ago 10
Python Question

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, e.g. (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). My solution would be (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

Answer

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 )