So programming languages are moving away from the logical operators and toward the English words and / or, fwict. The only loss from this (other than some disk space) is how the operators correspond to their bitwise counterparts.
Both & and && are doing the same thing, in terms of how they go from input to output. && is for booleans, and & is for sequences of bits, but both return True / 1 if and only if both operands are True / 1, False / 0 otherwise.
Same with || and |. Both return True / 1 if either operand is True / 1, only False / 0 if neither is True.
And really, True and False are just special cases of 1 and 0. They just plain were 1 and 0, back in the day.
So = is to == as & is to &&, as | is to ||, as ! is to ~, and in theory ^ and ^^ but I'm not sure if anyone lets you use ^^ for logical xor.
Basically, for every combination of inputs, there's an operator that returns True / 1. Except False and False / 0 and 0, but there is a logic gate for that in your CPU and you can just say not and (aka nand) for that, if you really need it. (I actually use x&~y quite a bit, just to turn off specific bits, but I don't think that uses nand under the hood? Well, OK, there's a proof that you can use nands to get all the other operations, so anything could be using nand under the hood, but I digress.).
I I suppose you use the logical operators when you need a boolean. You use the bitwise operators when you want a number. The key thing is understanding how numbers are sequences of booleans. If you think of an int as something like an array of bits, it makes more sense.
And like Camlorn said, the ability to work with binary / hexadecimal is essential to this. 1&2 == 0, because 1 and 2 have no bits in common. 1&3 == 1, because they only have the 1 bit in common. And 1|2 == 3, just like 1|3, because the 1 and 2 bits are there in both cases, but no others.
The thing that threw me was realizing that we have a bitwise xor, but no one ever teaches logical xor. Then I discovered that Python does not have a logical xor, but angelscript does, and xor is really useful for side-scrollers. Ah, well. What's a little extra code? That's how everything works, isn't it?
看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
George... Don't do that.