0

I want to do a bitwise not in Python, but withouth taking care of the sign, as C would do. For example:

>>> x = 4
>>> y = ~x
>>> bin(x)
'0b100'
>>> bin(y)
'0b101'

In the above code, y is 0b101, but I want it to be 0b011, literally the bitwise not applied to number 4. How can I do this?

Dan
  • 2,452
  • 20
  • 45
  • C wouldn't do what you describe. ~4 in C does not give 3. – khelwood Jan 18 '22 at 10:34
  • 2
    `bin(y)` is not `0b101`, it's `-0b101`, aka `0b..111111011` with an infinite prefix of ones. Putting that aside, can you give more examples of what inputs and outputs you want? – harold Jan 18 '22 at 10:44

2 Answers2

2

Since Python ints are both signed and not a defined size of bits, the easiest way is to just XOR with an all 1's mask of the required bit length.

For example to get a NOT for 4 bits:

bin(x ^ 0b1111)

Test:

>>> x = 4
>>> bin(x)
'0b100'
>>> bin(x ^ 0b1111)
'0b1011'
vaizki
  • 1,678
  • 1
  • 9
  • 12
2

you could generate a mask of the bit length of x and xor that with x:

x = 4  # 0b100
width = x.bit_length()
mask = (1 << width) - 1  # mask = 0b111
y = x ^ mask
print(f"{y:0{width}b}")  # '011'
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111