0

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?
1
  • May I ask why I was voted down? Commented Sep 4, 2015 at 14:35

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.