0
Why the value of ~True
is -2
and that of ~False
is -1
?
The logical operator equivalent not
, in not True
, results in False
and vice versa.
0
Why the value of ~True
is -2
and that of ~False
is -1
?
The logical operator equivalent not
, in not True
, results in False
and vice versa.
2
Do:
print(~1)
print(~0)
Same thing, right? After all True
vale 1
and False
vale 0
. Therefore he applied the complement operation on these numbers when using the boolean literals.
The complement operator inverts the number bits, all the existing bits but compensating with what is called complement, or as one usually learns in school, the "vai um". It does not exchange the signal, or invert the number by some criterion, it inverts the bits that make up the number, even because for all purposes numbers in the computer are only bit sequence.
So when it has a bit 0 it turns 1, but when the bit is 1 it turns 0 and goes one, so it changes the bit of higher magnitude then it should turn 10, which turning into decimal gives 2.
The conversion occurs even with the signal bit if it is positive or negative, and what was positive turns negative.
Then 0 turns -1, and 1 turns -2 (-10 in binary).
The decimal formula even to find the correct value is -(valor + 1)
.
Try this to see in binary:
print(bin(1))
print(bin(0))
print(bin(~1))
print(bin(~0))
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
The complement operator is not the same as the negation relational operator, so the results are different. At a boolean value the normal is to use the negation operator that gives the expected and already known result by AP.
Python is a strong typing language, but in the mucho, has exceptions, otherwise this operation would not even be possible.
Browser other questions tagged python operators bitwise
You are not signed in. Login or sign up in order to post.
Hello @Maniero! In the Python documentation is written "The unary ~ (invert) Operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral Numbers." My point is this: ~60 gives -61 for this formula. But, if you do the "inversion" bit by bit, it would give 1100 0011, because 60 is 0011 1100. So, what is the meaning of the value -61 (which is correct) if the "inversion" of the bits would give 195?
– Carlos Sanches
Law again, it’s not just inversion, it’s inversion with complement.
– Maniero
Okay. But, what is the meaning of this inversion with complement? And how was the expression -(x+1) deduced? Is there any text you recommend that explains this in detail at a beginner/intermediate level?
– Carlos Sanches
The same one you learned in math, when you add 7 to 5 doesn’t give 2, you give 12, then you need add-on. The documentation gives the formula accurately:
-(x+1)
– Maniero