Following on from last week’s look at the bitwise AND operator, this week I’m going to look at bitwise OR and provide an example of how you can use it.
Bitwise OR is represented by the | symbol.
Can I see an example?
130 | 10 = 138
What is this actually doing?
Bitwise OR compares each bit setting and if either one is set, sets the corresponding output bit to 1. So in the example above, we can see the actual bit comparisons as follows:
10000010 //130
00001010 //10
________
10001010 //138
Note that it doesn’t matter if one or both bits are set in what we are comparing. As long as either one is set, the output bit is set to 1.
What would I use bitwise OR for?
OK, an example follows – it’s much easier to understand the usefulness of these operators when you see them in action.
Turning on an individual bit
Remember last week we used bitwise AND to turn off an individual bit? Well bitwise OR allows you to do the opposite. By using a mask with the bits set that we want to turn on, we can modify the individual bits in any byte.
Let’s say we have a byte, containing 8 bits, which are used as true/false values. Without changing the settings of any of the other bits, we want to set the first bit to be true. We apply the mask 1 (decimal) as follows:
11000100 // 196
00000001 // 1
________
11000101 // 197
The result is that the first bit (that is, the right-most bit) is now set to 1, and the other bit settings remain unchanged.
That’s all there is to it!
Next week we’ll look at bitwise XOR.