How to Use the Bitwise & Operator in C Programming

By Dan Gookin

Like the bitwise OR operator in C programming, the bitwise AND operator, &, also affects bits in a byte. Unlike OR, which sets bits, the AND operation masks bit values. It’s easier to show you a program example than to fully describe what mask means.

PUTTING PUTCHAR() TO WORK

#include <stdio.h>
int main()
{
  int ch;
  printf("Press Enter: ");
  getchar();
  ch = 'H';
  putchar(ch);
  ch = 'i';
  putchar(ch);
  putchar('!');
  return(0);
}

Exercise 1: Modify the source code from Putting putchar() to Work so that a bitwise AND operation takes place instead of a bitwise OR. Change the constant SET in Line 2 to the value 223. Change the | (bitwise OR) in Line 12 to the & (bitwise AND). And finally, change the printf() statement in Line 15 so that the | is replaced by the & character. Build and run.

Here’s the output for the value 255 (all bits set):

Type a value from 0 to 255: 255
 11111111 255
& 11011111 223
= 11011111 223

The bitwise & masks out the sixth bit, causing its value to be reset to 0 in the final calculation. No other bits are affected. To see more examples, try the values 170 and 85. Watch how the bits fall through the mask.

CHARACTER VARIABLE MADNESS

#include <stdio.h>
int main()
{
  char a,b,c,d;
  a = 'W';
  b = a + 24;
  c = b + 8;
  d = 'n';
  printf("%c%c%c%c",a,b,c,d);
  return(0);
}

Exercise 2: Modify the source code from Character Variable Madness so that a bitwise AND operation takes place instead of a bitwise OR. Change Line 9 so that the printf() statement prompts: “Type in some text:” Change Line 14, replacing | with & and replacing the value 32 with 223. Build and run.

Just as the bitwise OR sets the sixth bit to convert uppercase text to lowercase, masking the sixth bit with a bitwise AND converts lowercase text into uppercase. Of course, the bitwise AND also masks out the space character, changing its value to 0, which isn’t a displayable character.

Exercise 3: Modify your solution for Exercise 2 so that only letters of the alphabet are affected.