William Fernandes William Fernandes - 3 months ago 6
Python Question

Signed binary to int in Python

Lets say I have the signed binary value

11111
, which equals
-1
. But
int("0b11111", 2)
returns
31
instead.

How would I have it return the correct signed value?

BPL BPL
Answer

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))