How to Use the Bitwise | Operator in C Programming - dummies

How to Use the Bitwise | Operator in C Programming

By Dan Gookin

You’re already familiar with C programming’s decision-making logical operators: && for AND and || for OR. In the && evaluation, both items must be true for the statement to be evaluated as true; for the || evaluation, only one of the items must be true.

At the atomic level, the operators & and | perform similar operations, but on a bit-by-bit basis. The net effect is that you can use the & and | operators to manipulate individual bits:

The | is the bitwise OR operator, also known as the inclusive OR.

The & is the bitwise AND operator.

The OR Set demonstrates how to use the bitwise OR operator to set bits in a byte. The OR value is defined as the constant SET at Line 2. It’s binary 00100000.


#include <stdio.h>
#define SET 32
char *binbin(int n);
int main()
 int bor,result;
 printf("Type a value from 0 to 255: ");
 result = bor | SET;
char *binbin(int n)
 static char bin[9];
 int x;
 bin[x] = n & 0x80 ? '1' : '0';
 n <<= 1;
 bin[x] = '';

Line 12 calculates the bitwise OR operation between a value input, bor, and the SET constant. The result is displayed in three columns: operator, binary string, and decimal value. The end result of the operation is that the bits set to 1 in the SET value will also be set to 1 in the bor value.

Exercise 1: Type the source code from The OR Set into your editor to create a new program. Build and run the program.

Here’s the output for the value 65:

Type a value from 0 to 255: 65
 01000001 65
| 00100000 32
= 01100001 97

You can see in the binary output how the sixth bit is set in the result.

What does that mean?

It means that you can manipulate values at the binary level, which does have interesting consequences for certain mathematical operations, as shown in Up with That Text.


#include <stdio.h>
int main()
 char input[64];
 int ch;
 int x = 0;
 printf("Type in ALL CAPS: ");
 while(input[x] != 'n')
 ch = input[x] | 32;

Exercise 2: Start a new project by using the source code shown in Up with That Text. Build and run.

Because of the way the ASCII codes map between upper- and lowercase characters, you can switch the case by simply setting the sixth bit in a byte.