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
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.
3 Comments
Thor Correia
Thanks! Um, how would I tell python to negatate 0b10101111?
Greg Hewgill
Use the
- unary operator. So a = 0b10101111; print(a, -a)Greg Hewgill
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."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.