What is & or | or ^?


#1

I can't figure out what they do. It's talking about turning bits on and stuff and it's all so confusing.

EDIT: Figured it out by myself.


#2

The ampersand (&) along with the (|) are bool operators.

The & is the bitwise and and the | is the bitwise or operators.


#3

That doesn't help me at all. I know that they're bitwise operators and stuff. I was asking for a little more explanation on what they do. Fortunately, I figured it out by myself.


#4

If you've figured things out, it would be greatly helpful for others who come later to provide your own explanation :smile: Kind of like how "nvm fixed it" isn't a very helpful thread-closure on StackExchange.

Python.org provides this article with more explanations, but even that's still a bit high-level. So let me see if I can't make things just a little clearer.

Let's assume two variables, A and B, both only containing one bit (1 or 0). I wish we could make tables here :smiley:

AND operator, A&B, quite literally means that both A and B must be 1 to return a 1:

  • A = 0, B = 0, results in 0
  • A = 0, B = 1, results in 0
  • A = 1, B = 0, results in 0
  • A = 1, B = 1, results in 1

OR operator, A|B, literally means that either A or B must be 1 to return a 1:

  • A = 0, B = 0, results in 0
  • A = 0, B = 1, results in 1
  • A = 1, B = 0, results in 1
  • A = 1, B = 1, results in 1

XOR (exclusive OR) operator, A^B, means that only A or B must be 1 to return a 1:

  • A = 0, B = 0, results in 0
  • A = 0, B = 1, results in 1
  • A = 1, B = 0, results in 1
  • A = 1, B = 1, results in 0

Now, let's apply some of this to actual bytes of data. Remember, the operators are still BITwise, so:

  • 1001 & 1110 = 1000, because only the fourth bit (from the right) is "1" in both nibbles (half a byte).
  • 1001 | 1110 = 1111, because between the two nibbles every bit is "1" at least once.
  • 1001 ^ 1110 = 0110, because between the two nibbles only the third and second bits are "1" once.

I don't understand 13/14