Search code examples
pythonbinaryintsigned

5-bit signed binary to int


My code has to read 5-bit signed binary values. Let's say it reads a 11111, which would be two's complement -1. But int("0b11111", 2) returns 31 instead.

How can I parse the correct value?


Solution

  • Here's a possible solution testing all 5-length binary numbers of your future emulator:

    import itertools
    
    
    def two_complement(value, length):
        if (value & (1 << (length - 1))) != 0:
            value = value - (1 << length)
        return value
    
    opcodes_emulator = ["".join(seq) for seq in itertools.product("01", repeat=5)]
    
    for my_string in opcodes_emulator:
        print my_string, two_complement(int(my_string, 2), len(my_string))