1

Why is x & 0 different from x & ~1?

Shouldn't ~1 and 0 be the same since 0 is the complement of ~1?

x = 21
print(f"x = {bin(x)}")
print(f"x & 0 = {bin(x & 0)}")
print(f"x & ~1 = {bin(x & ~1)}")

results in

x = 0b10101
x & 0 = 0b0
x & ~1 = 0b10100
Bracktus
  • 319
  • 1
  • 2
  • 8
  • 2
    Have you tried `print(bin(~1))`? – Mark Ransom Jun 25 '21 at 17:04
  • @EugeneSh. not quite true in Python, since integers are arbitrary length you'd need an infinite number of leading `1`s. – Mark Ransom Jun 25 '21 at 17:05
  • @EugeneSh. That's 1s complement; Python doesn't use that. `~x` is equal to `-(x+1)` [for an integer `x`](https://github.com/python/cpython/blob/32bd68c839adb7b42af12366ab0892303115d1d1/Objects/longobject.c#L4300-L4303). – Mustafa Aydın Jun 25 '21 at 17:11
  • @MarkRansom Actually I have missed the fact the question is for Python, so I guess my comment is inaccurate. I will remove it to prevent confusion. – Eugene Sh. Jun 25 '21 at 17:13
  • Thanks jxh and EugeneSh, this makes sense to me. – Bracktus Jun 25 '21 at 17:14

2 Answers2

1

You are getting confused between ~and not here,

x & (not 1) will be equal to 0

as not 1 is 0 but ~1 is -0b10 which is -2 for a 2-bit representation.

You can read more on ~ operator in this link

Shreyansh
  • 458
  • 4
  • 11
0

~ and & are bitwise operations, not logical operations. The logical expression "x and False" indeed yields False, as does "not True":

print x and False
print x and not True