def create_button_code(at: int = 0, home: int = 0, joystick: int = 0, zero_halt: int = 0) -> int: assert at in range(4), "Must be in the range 0-3." assert home in range(4), "Must be in the range 0-3." assert joystick in range(4), "Must be in the range 0-3." assert zero_halt == 0 or zero_halt == 1, "Must be 0 or 1." button_code = 0 # bit masks BITMASK_AT = 0x03 # 00000011 BITMASK_HOME = 0x0C # 00001100 BITMASK_JS = 0x30 # 00110000 BITMASK_ZERO = 0xC0 # 11000000 # set bits button_code &= ~BITMASK_AT button_code |= at & BITMASK_AT button_code &= ~BITMASK_HOME button_code |= (home << 2) & BITMASK_HOME button_code &= ~BITMASK_JS button_code |= (joystick << 4) & BITMASK_JS button_code &= ~BITMASK_ZERO button_code |= (zero_halt << 6) & BITMASK_ZERO return button_code def main(): button_code = create_button_code(at=1, home=1) print(button_code) # prints 5 if __name__ == "__main__": main()