Bitwise Operators: Difference between revisions
m
→XOR: fixed formatting inconsistency
Puppydrum64 (talk | contribs) m (→Random Chance: Formatting consistency) |
Puppydrum64 (talk | contribs) m (→XOR: fixed formatting inconsistency) |
||
(9 intermediate revisions by the same user not shown) | |||
Line 1:
[[Category:Encyclopedia]]
As the name implies, bitwise operators look at the individual bits of a number. Computers store everything in binary, therefore bitwise operations can be used on all types of data, whether the source code displays the data in binary or not. The computer will look at those numbers' binary representations to calculate the result.
Line 13 ⟶ 11:
</pre>
A few properties of <code>AND</code> that aren't readily apparent.
For all numbers A:
* <code>A & 0 = 0</code>
* <code>A & A = A</code>
* <code>A & -1 = A (remember that -1 = FF)</code>
* Every 4 binary digits of A and B can be <code>AND</code>ed separately and concatenated, and the result is the same.
Line 72 ⟶ 71:
When we say "or" in the English language, we usually mean "one or the other, but not both." This isn't the case in programming. That's actually a different operator which will be covered later.
A few properties of OR that aren't readily apparent.
For all numbers A:
* <code>A | 0 = A</code>
* <code>A | A = A</code>
* <code>A | -1 = -1</code>
The first property implies that if a subset of a byte is a sequence of zeroes, then <code>OR</code>ing that sequence of zeroes with any bit combination will result in the same bit combination. For example:
Line 86 ⟶ 87:
===Failsafes===
Bits that get <code>OR</code>ed with 1 always equal 1, regardless of their original value. If you have a variable that you want to guarantee at least certain bits are set, you can OR them with those bits. The nice thing about this method is that the actual value of that variable need not be compared to anything. Those bits will get set either way.
===Combining two values without addition===
Line 104 ⟶ 105:
* A bit <code>XOR</code>'d with 1 will flip. A bit <code>XOR</code>'d with zero won't change.
* A bitwise <code>NOT</code> is the same as <code>XOR -1</code>.
* <code>A ^ A = 0</code>. Furthermore, if <code>A ^ B = 0</code>, then <code>A = B</code>.
* If <code>((A ^ B) & C) = 0</code>, then A and B both share the bits of C in common.
Line 112 ⟶ 115:
==NOT==
A bitwise <code>NOT</code>, or <code>~</code> takes one number as an argument and flips all its bits. This has its uses, especially when reading video game controllers, but is a little more limited than the others.
Among <code>AND</code>, <code>OR</code>, <code>XOR</code>, and <code>NOT</code>, only <code>XOR</code> and <code>NOT</code> are reversible.
==Citations==
#[[http://www.6502.org/tutorials/compare_beyond.html Beyond 8-Bit Unsigned Comparisons by Bruce Clark]]
|