Bitwise Operators – Free Guide

Bitwise OperatorsI have an exciting new eGuide available.

Most of this info is available in various places on my site, but I’ve collated it all together in one document, and updated it, so it’s easier for you to use.

What does it cover?

It’s a no-jargon guide to the four bitwise operators in C (AND, OR, XOR, NOT).

Not only does it walk you through exactly how each one works, with examples, it also provides explanations of how they would be used in programming and (as if that wasn’t enough), there’s a handy quick-start guide at the end which you can refer to so you know exactly when to use each operator and why.

It’s all written in a no-nonsense, easy to read format, that makes programming the joy it should be.

Hurrah to that, I say.




Bitwise OR

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.