Bitwise Operators
Bitwise Operators
We commonly use the binary operators && and ||, which take the logical and and logical or of two
boolean expressions.
Since boolean logic can work with single bits, C/Java/Python (and most languages) provides
operators that work on individual bits within a variable.
As we learned earlier in the semester, if we store an int in binary with the value 47, its last eight
binary bits are as follows:
00101111
Similarly, 72 in binary is
01001000.
Bitwise operators would take each corresponding bit in the two input numbers and calculate the
output of the same operation on each set of bits.
For example, a bitwise AND is represented with a single ampersand sign: &. This operation is
carried out by taking the and of two bits. If both bits are one, the answer is one. Otherwise, the
answer is zero.
00101111
&01001000
---------------------
0 0 0 0 1 0 0 0 (which has a value of 8.)
Now, let’s calculate the other bitwise operations between 47 and 72:
00101111
| 01001000
---------------------
0 1 1 0 1 1 1 1 (which has a value of 111.)
00101111
^ 01001000
---------------------
0 1 1 0 0 1 1 1 (which has a value of 103.)
47 << 2
47 >> 3
72 << 1
Understanding how bitwise operators work in programming languages is useful because the
descriptions of most modern day symmetric ciphers include operations on the bits in blocks of the
cipher. In order to code up any of these ideas, it would be best to use bit-wise operators.
The most common bitwise operator used is xor, because xoring some input with a secret key (that
is random) effectively randomizes the output.
In dealing with moving bits around, the most common operations would be left or right shifts.