1

In python, 0b01001011 would be 75, which also works in Two's Complement. But 0b10101001 would be 169, where as in with Two's Complement it would be -87. How do I express Two's Complement binary literals?

2 Answers 2

3

You represent negative binary literals with a negative sign, like this:

>>> -0b1010111
-87

Python's integers are not fixed width, so there is no "two's complement" as such.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Um, how would I tell python to negatate 0b10101111?
Use the - unary operator. So a = 0b10101111; print(a, -a)
Sure, Python actually defines the ~ operator in terms of unary -: "The unary ~ (invert) operator yields the bitwise inversion of its plain or long integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers."
0

You can use the Binary fractions package. This package implements TwosComplement with binary integers and binary fractions. You can convert binary-fraction strings into their twos complement and vice-versa

Example:

>>> from binary_fractions import TwosComplement, Binary
>>> int(Binary("01001011"))
75
>>> int(Binary("10101001"))
169
>>> TwosComplement("10101001").to_float()
-87.0

PS: Shameless plug, I'm the author of this package.

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.