Is there an easy way to produce a one's complement in python?
For instance, if you take the hex value 0x9E
, I need to convert it to 0x61
.
I need to swap the binary 1's for 0's and 0's for 1's. It feels like this should be simple.
Python's ~ (bitwise NOT) operator returns the 1's complement of the number. 14 is (1110) in its 2's complement binary form. Here, ~14 would invert (i.e. 1's complement) all the bits in this form to 0001.
When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex() function to convert values to hexadecimal format for display purposes.
Two's Complement binary for Negative Integers: So -1 is complement(1 - 1) = complement(0) = "11111111", and -10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110". This means that negative numbers go all the way down to -128 ("10000000"). Of course, Python doesn't use 8-bit numbers.
Bitwise one's complement operator (~) Bitwise one's compliment operator will invert the binary bits. If a bit is 1, it will change it to 0. If the bit is 0, it will change it to 1.
Hah. just found out that python bin()
return a string!
so we can have some fun at this!
for x in numbers: # numbers is a list of int
b = bin(x)
#print b # e.g. String 0b1011100101
b = b.replace('0', 'x')
b = b.replace('1', '0')
b = b.replace('x', '1')
b = b.replace('1b', '0b')
#print b # String 0b0100011010
print int(b, 2) # the decimal representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With