How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with Python

1 Answer

0 votes
def print_bits(value: int, width: int) -> None:
    print(f"{value:0{width}b}", end='')


def exact_bit_set(pos1: int, pos2: int, value: int) -> bool:
    """
    Returns True only if:

      • pos1 and pos2 are valid (>= 0, < 64, and not equal)
      • value has EXACTLY those two bits set
      • all other bits are OFF

    Bit positions are ZERO‑BASED from the RIGHT (LSB = position 0).
    """
    if pos1 < 0 or pos2 < 0 or pos1 >= 64 or pos2 >= 64:
        return False

    if pos1 == pos2:
        return False

    mask = (1 << pos1) | (1 << pos2)
    
    return value == mask


class Test:
    def __init__(self, value, x, y, width):
        self.value = value
        self.x = x
        self.y = y
        self.width = width


tests = [
    Test(0b1000010000, 4, 9, 10),
    Test(0b0010000010, 1, 7, 10),
    Test(0b0000100100, 2, 5, 10),
    Test(0b1000010000, 3, 9, 10),
    Test(0b1001010000, 4, 9, 10),
    Test(0b1111111111, 4, 9, 10),
    Test(0b0000000000, 4, 9, 10),
    Test(0b1000010000, 4, 8, 10),
    Test(1,            0, 0, 1),
    Test(1,            0, 1, 1),
    Test(0,            1, 1, 1),
]

for t in tests:
    print_bits(t.value, t.width)
    print(f"  bits({t.x}, {t.y})  ->  {'true' if exact_bit_set(t.x, t.y, t.value) else 'false'}")


'''
run:

1000010000  bits(4, 9)  ->  true
0010000010  bits(1, 7)  ->  true
0000100100  bits(2, 5)  ->  true
1000010000  bits(3, 9)  ->  false
1001010000  bits(4, 9)  ->  false
1111111111  bits(4, 9)  ->  false
0000000000  bits(4, 9)  ->  false
1000010000  bits(4, 8)  ->  false
1  bits(0, 0)  ->  false
1  bits(0, 1)  ->  false
0  bits(1, 1)  ->  false

'''

 



answered Apr 3 by avibootz

Related questions

...