This answer demonstrates the negation of the LSB of an integer. This approach did not produce expected results when using negative (signed) integers. Let's look at some code:
a = 4
print()
print("a: " + str(a))
print("binary version of a: " + bin(a))
a = a | 1
print("binary version of a after negation of LSB: " + bin(a))
print("a after negation of LSB: " + str(a))
print()
b = 5
print("b: " + str(b))
print("binary version of b: " + bin(b))
b = b & ~1
print("binary version of b after negation of LSB: " + bin(b))
print("b after negation of LSB: " + str(b))
print()
c = -4
print("c: " + str(c))
print("binary version of c: " + bin(c))
c = c | 1
print("binary version of c after negation of LSB: " + bin(c))
print("c after negation of LSB: " + str(c))
print()
d = -5
print("d: " + str(d))
print("binary version of d: " + bin(d))
d = d & ~1
print("binary version of d after negation of LSB: " + bin(d))
print("d after negation of LSB: " + str(d))
The expected value of c
after the negation of the LSB is -5 and not -3. Similarly, the expected value of d
after the negation of the LSB is -4 and not -6. Why don't the actual values of c
and d
match their expected values?