How many switches differ
Two configuration fields are compared to see how far apart they are: the count of bit positions where the two disagree.
- Compare the two fields bit by bit.
- Return how many positions hold different bits.
- Two identical fields differ in nothing.
- Both values are zero or more.
differing_bits(before: int, after: int) → int
Where you start
def differing_bits(before: int, after: int) -> int:
Worked examples
| Call | Result |
|---|---|
differing_bits(1, 4) | 2 |
differing_bits(3, 1) | 1 |
differing_bits(0, 0) | 0 |
differing_bits(7, 7) | 0 |
Hint
Exclusive-or sets exactly the bits where the two disagree. Then it is only a matter of counting the set bits in that.
Reference solution in Python
def differing_bits(before: int, after: int) -> int:
differing = before ^ after
count = 0
while differing > 0:
count += differing & 1
differing >>= 1
return count