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

# How to Use the Bitwise | Operator in C Programming

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.

THE OR SET

```#include <stdio.h>
#define SET 32
char *binbin(int n);
int main()
{
int bor,result;
printf("Type a value from 0 to 255: ");
scanf("%d",&bor);
result = bor | SET;
printf("t%st%dn",binbin(bor),bor);
printf("|t%st%dn",binbin(SET),SET);
printf("=t%st%dn",binbin(result),result);
return(0);
}
char *binbin(int n)
{
static char bin;
int x;
for(x=0;x<8;x++)
{
bin[x] = n & 0x80 ? '1' : '0';
n <<= 1;
}
bin[x] = '';
return(bin);
}```

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.

UP WITH THAT TEXT

```#include <stdio.h>
int main()
{
char input;
int ch;
int x = 0;
printf("Type in ALL CAPS: ");
fgets(input,63,stdin);
while(input[x] != 'n')
{
ch = input[x] | 32;
putchar(ch);
x++;
}
putchar('n');
return(0);
}```

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.