Reputation: 3221
Given a positive integer such as 171 and a "register" size, e.g. 8.
I want the integer which is represented by the binary representation of 171, i.e. '0b10101011' interpreted as twos complement.
In the present case, the 171 should become -85. It is negative because given the "register" size 8, the MSB is 1.
I hope I managed to explain my problem. How can I do this conversion?
What I tried:
size = 8
value = 171
b = bin(value)
if b[len(b)-size] == '1':
print "signed"
# What to do next?
Upvotes: 0
Views: 4469
Reputation: 13425
You don't need binary conversion to achieve that:
>>> size = 8
>>> value = 171
>>> unsigned = value % 2**size
>>> signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned
>>> signed
-85
Upvotes: 3
Reputation: 185
There are probably a hundred different ways to do this. Here are a couple.
If the size is a multiple of 8, then something like this will do the job:
x = int.from_bytes(value.to_bytes(size // 8, byteorder='big'), byteorder='big', signed=True)
If the size is not a multiple of 8, then you can do something like this:
mask = 1 << (size - 1)
x = (value ^ mask) - mask
Both assume the value isn't too big to fit into the "register".
Upvotes: 2