1

I am trying to use the bitwise not operator to flip the bits in 1.

I start with 1 (00000001) and add ~.

x = ~1
print(f'{x:08b}')

Result is -0000010.

Everything online tells me the result should be 11111110. Not sure what I can do wrong with putting ~ in front of a number.

I tried adding a step to make sure 1 shows up as 00000001, and it did:

a = 1
print(f'{a:08b}')
x = ~a
print(f'{x:08b}')

Really not sure how I can go wrong on this...

newbie54
  • 23
  • 4

1 Answers1

2

https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1).

So it's behaving as expected, printing "negative-of-a positive 2's complement". It doesn't print in 2's complement negative because: Format negative integers in two's complement representation

Kache
  • 15,647
  • 12
  • 51
  • 79
  • So how do I get the inverse of my bits as I want? I'm looking at this post (https://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-tilde-work) and the top answers also manage to flip numbers by using the tilde. Why does that not work here? – newbie54 May 10 '23 at 20:08
  • 2
    you mean this `print(f'{x & 0xFF:08b}')`? – Marcin Orlowski May 10 '23 at 20:11
  • That's it! Why do I not get that by just using ~1? – newbie54 May 10 '23 at 20:13
  • 1
    Because you can't print an infinite number of 1s easily :) – Mark Tolonen May 10 '23 at 20:13
  • That would indeed be rather tiresome, to watch an infinite number of 1's appear on my screen! But I thought bits were specifically 8 binary spaces only. How come this is infinite? (Sorry, just starting out, very confused and learning on my own so no one else I can ask!) – newbie54 May 10 '23 at 20:17
  • 2
    Python integers are infinite precision. Without a mask it doesn't know how many bits to print, so it prints the negative value if the number is negative. The mask makes the number positive and limits the number of bits in the result. – Mark Tolonen May 10 '23 at 20:21
  • 1
    A bit is one "binary space" and a byte is 8 bits. But as @MarkTolonen says, a Python integer can be made of arbitrarily many bytes. – slothrop May 10 '23 at 20:24
  • I see. I'm reading about the operators but I suppose I should look into masks first, mayhap. Thanks for explaining! – newbie54 May 10 '23 at 20:32