Bitwise AND

I’m going to spend the next few weeks taking a look at the bitwise operators (AND, NOT, OR, XOR), and how they are used in C/C++.

How often you are faced with problems that use these operators depends on the field you are working in, and the coding preferences of the people that have gone before you. It’s entirely possible to code in C++ for years and never need to know the ins and outs of bits in a byte.

The bitwise operators enable you to work at a very fine-grained level, which is advantageous when you are dealing with limited space, or sending messages with limited capacity.

So let’s get going.

Bitwise AND is represented by the & symbol.

Can I see an example?

128 & 10 = 0

What is this actually doing?

Bitwise AND compares each bit setting and if they match, sets the corresponding output bit to 1. So in the example above, we can see the actual bit comparisons as follows:

10000000    //128
00001010    //10
________
00000000    //0

What would I use bitwise AND for?

Good question. The above example seems totally counter-intuitive, and quite clearly would make you wonder what use this would ever actually have. Below are two examples of using the & operator that should enable you to see its usefulness more clearly.

1. Bit masking to check status

Let’s say I am using a byte to hold the true/false status of 8 items. I want to know if item 5 is true (set to 1). Since I can’t read bits individually, I can simply AND my byte with the appropriate mask and test the result. My mask in this case is decimal 16 (00010000).

01101011    //107
00010000    //16
________
00000000    //0

The result is 0 if bit 5 is not set.

01111011    //123
00010000    //16
________
00010000    //16

And the result is 16 (i.e. the value of the mask) if bit 5 is set.

2. Turning off an individual bit

Now let’s say that I want to turn off bit 5. I can do this with the mask 239  (11101111):

01111011    //123
11101111    //239
________

01101011    //107

Can you see what’s happened here? The bitwise AND comparison checks each bit and sets the result to 1 if they match. Therefore, if I want to turn off bit 5, all I need to do is set my mask to contain zero at this position. That way, bit 5 will never be set to 1 in the result. Setting everything else to 1 in the mask ensures that all other bits remain unchanged.

Note that you can’t turn a bit on with the AND operator, since you must have two values of 1 to get the output of 1.

Next week we’ll take a look at bitwise OR.