Reputation: 23
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...
Upvotes: 1
Views: 190
Reputation: 16687
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
Upvotes: 2