Bracktus
Bracktus

Reputation: 349

Why is (x & 0) different from (x & ~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

Upvotes: 1

Views: 93

Answers (2)

Erpelstolz
Erpelstolz

Reputation: 1

~ 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

Upvotes: 0

Shreyansh
Shreyansh

Reputation: 476

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

Upvotes: 1

Related Questions