0

I have calculated the 2's complement of a binary number and represented it in the Binary format. Now, I am trying to convert the 18-bit Signed Binary Number to decimal numbers (-131072 to +131072).

When I use the int function it only gives unsigend values:-

number = 111111111111111110
print(int(str(number), 2))

Output = 262142

Any suggestions would be highly appreciated. Thanks!

5
  • Does this answer your question? Converting binary representation to signed 64 bit integer in Python Commented Jan 5, 2022 at 6:48
  • You could have written the number literal as 0b111111111111111110 and saved some time on conversions. Commented Jan 5, 2022 at 6:49
  • @jtbandes I have tried that, but it uses a built in library. Is it possible to do without it? Commented Jan 5, 2022 at 6:51
  • 1
    The code in your question parses a digit sequence as decimal, then unparses it as decimal, then parses the unparsed digit sequence as binary. If you just write 0b111111111111111110 as the other user suggests, you just parse the digit sequence once as binary. Commented Jan 5, 2022 at 7:27
  • This isn't "using a built-in library" any more than your original code, which already makes use of multiple forms of built-in digit sequence parsing. Commented Jan 5, 2022 at 7:28

2 Answers 2

1

You could implement the signed conversion manually by treating the high bit as negative:

>>> def foo(x):
...   return (x & ((1<<17) - 1)) - (x & (1<<17))
>>> foo(0b010000000000000000)
65536
>>> foo(0b100000000000000000)
-131072
>>> foo(0b111111111111111111)
-1
Sign up to request clarification or add additional context in comments.

Comments

1

Given the string representation of a binary number, you can do this:

def todecimal(x, bits):
    assert len(x) <= bits
    n = int(x, 2)
    s = 1 << (bits - 1)
    return (n & s - 1) - (n & s)

print(todecimal('011111111111111111', 18))
print(todecimal('1', 18))
print(todecimal('100000000000000000', 18))

Note that the number of characters in the string must be less than or equal to the number of bits represented by the string.

Output:

131071
1
-131072

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.