Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From hexadecimal to one's complement in Python

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.

like image 831
user1841870 Avatar asked Nov 21 '12 12:11

user1841870


People also ask

How do I get 1's complement in Python?

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.

How do you convert hexadecimal to Python?

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.

How do you use complement in Python?

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.

How do you use Bitwise complement in Python?

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.


1 Answers

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
like image 159
gcb Avatar answered Oct 13 '22 17:10

gcb