0

I am doing some calculations and I was wondering how you can invert a byte in python.

For example:

0b11111111 should be flipped to 0b00000000.

I have tried turning into a string and flipping it then but I cant somehow turn it back into a Integer.

Also, I want to add that the ~ does not work, as it simply just makes the same number but negative

2 Answers2

1
 bin(0b11010111 ^ 0b11111111) // bit subtraction
 # Result
 # bin(0b11010111 ^ 0b11111111)
 #'0b101000'
 # for each bit subtraction with 1 occur
1

To explain why ~ "dit not work": you want to invert all bits in a byte (8-bits), but the 0b.... value is not a byte, but an int which has more bits than just 8. ~var inverts all bits in an integer. You can clear all bits except the lowest 8 with a mask to get the result you expect:

MASK8 = 0b11111111  # or 255 decimal

v = 0b11101110                                                                                                                                                    
inv = ~v & MASK8    # 0b10001
VPfB
  • 14,927
  • 6
  • 41
  • 75