Alex Alex - 1 year ago 85
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)


but I wonder if there is a more elegant way to do this (without using floats etc.).


Answer Source

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 )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download