So far we have covered how binary works. With these bits we can represent different values. We looked at how a set of characters would be “read” by a computer. However, what makes computers powerful is that they can do calculations extremely fast. In this section we’ll take a look at how a computer “thinks” and “creates”.
There are four main bit-level operations in C (and Java and many other languages.)
| is the symbol for OR
& is the symbol for AND
~ is the symbol for NOT
^ is the symbol for EXCLUSIVE OR
These are not to be confused by the boolean operations ||, &&, and ! which interestingly have some of the same names. The boolean operations are used for truth calculations, true or false. The bit-level operations are used to change one set of bits to another set of bits.
For now, let’s agree that integers can be represented with 32-bits. and those 32 bits can be represented in hex with 8 digits.
000000FF is a 32-bit integer with a base-ten value of 255 and a binary representation of 0000 0000 0000 0000 0000 0000 1111 1111. We can also represent this hex value as FF, or more commonly 0xFF. The 0x prefix tells us this is a hex value.
If we have values 0xFF and 0x11 we can perform bitwise operations on them as follows:
0xFF & 0x11 =
1111 1111
0001 0001 &
The & operator asks us to find all of the bit pairs that are ON between both numbers so our result will be:
0001 0001
This is because only the two bits where 1’s between both values. Let’s look at another example:
0xF1 & 0x33 =
1111 0001
0011 0011 &
0011 0001
So the operation 0xF1 & 0x33 = 0x31
The other bitwise operators do something similar.
| for binary OR the result in each position is 1 if one or both of the bits is 1, but will be 0 if both are 0.
^ for binary XOR the result in each position is 1 if only one of the bits is 1, but will be 0 if both are 0 or both are 1.
~ for unary operator NOT, each bit in one sequence will be “flipped”. 0’s turn into 1’s and 1’s intro 0’s. This is much different than the boolean operator !, which also is called NOT. You can do a little research on how they are different.
This is much easier to show with diagram, so please review the following short video: