Thor Correia
Thor Correia

Reputation: 1588

How do I express binary literals in Two's Complement in Python?

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?

Upvotes: 1

Views: 851

Answers (2)

Jonny Baron
Jonny Baron

Reputation: 61

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.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993881

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.

Upvotes: 3

Related Questions