====TLDR=============================================================
Curious about the behaviour of logical and bitwise logical operations on integers, i.e with
and
:= logical and
&
:= bitwise and
not
:= logical not
~
:= bitwise not
Can anyone explain why (2 and not 5) = False
, (2 and 5) = 5
,
(2 & 5) = 0
, (2 & ~5) = 2
, and (2 & not 5) = (2 and ~5) = -6
=====================================================================
Today in my computer science lecture (First Year Algorithm Design & Data Abstraction) we were going over the C logical operators. We're still early on in the course, so the information was relatively brief, but the idea was that boolean types are really just integers, where 0 is defined as false, and 1 is defined as true, however, the boolean value of any nonzero integer is also true - so 0 is false and anything else is true, simple enough.
Then we were given an example of using logical operators on numbers, like (2 && !5) = False
. This makes enough sense to me, 2 is true, and 5 is true, so not 5 is false, thus
(2 & !5)
<=>(True and False)
, which is false.
Bitwise operators are outside the scope of my course, however this got me curious, as I've been programming for 3 years now and I've never been taught about these properties of booleans, so I opened up my terminal to do some messing around with python, and got some unexpected results...
First, (2 and not 5)
evaluates to false
, as expected, however (2 and 5)
evaluates to 5
. Weird... but bool(2 and 5)
evaluates to true (evidently, as 5!=0
). So I guess this makes sense, but I don't know where the 5 is coming from, and there's more..
When performing a bitwise and 2 & 5
I get 0
, so false, and using bitwise operators to reproduce the original example "two and not five" as (2 & ~5)
produces 2
. Combining bitwise and logical operators is even more confusing...
(2 and ~5)
and (2 & not 5)
both produce -6
.
While I'm sure my confusion arises from ignorance to the mechanisms of logical and bitwise operations, I haven't been able to find an exact explanation of the behaviour I'm seeing here. If anyone could take the time to explain how this works, or point me in the direction of some reading that will help me understand, I'd greatly appreciate it.