C Exercise Example52
## C Programming Exercise - Example 52: Bitwise OR Operator (`|`)
In C programming, bitwise operators are used to perform operations at the binary level. This tutorial demonstrates how to use the **Bitwise OR operator (`|`)** and the **Bitwise OR assignment operator (`|=`)**.
---
### Introduction to Bitwise OR (`|`)
The bitwise OR operator (`|`) compares each bit of its first operand to the corresponding bit of its second operand. If either bit is `1`, the resulting bit is set to `1`. Otherwise, the resulting bit is set to `0`.
#### Truth Table for Bitwise OR:
| Operand A | Operand B | A | B (Result) |
| :---: | :---: | :---: |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
---
### Problem Description
Write a C program to demonstrate the usage of the bitwise OR operator (`|`) and the compound assignment operator (`|=`).
---
### Code Implementation
Below is the complete C source code. The program uses octal notation (`077`) and decimal integers to perform bitwise operations.
```c
#include
int main()
{
int a, b;
// 077 is an octal number.
// Octal 077 is equal to decimal 63 (7 * 8^1 + 7 * 8^0)
// Binary representation: 0011 1111
a = 077;
// Perform bitwise OR between 'a' and decimal 3
// 3 in binary: 0000 0011
// 0011 1111 | 0000 0011 = 0011 1111 (Decimal 63)
b = a | 3;
printf("The value of b is %d \n", b);
// Perform bitwise OR assignment: b = b | 7
// 7 in binary: 0000 0111
// 0011 1111 | 0000 0111 = 0011 1111 (Decimal 63)
b |= 7;
printf("The value of b is %d \n", b);
return 0;
}
```
---
### Output
When you compile and run the program, it produces the following output:
```text
The value of b is 63
The value of b is 63
```
---
### Detailed Analysis
Let's break down the binary operations step-by-step:
#### Step 1: Understanding Octal `077`
In C, any integer literal starting with a leading `0` is treated as an octal (base-8) number.
* $\text{Octal } 077 = (7 \times 8^1) + (7 \times 8^0) = 56 + 7 = 63 \text{ (Decimal)}$
* Binary representation of $63$ (using 8 bits): `0011 1111`
#### Step 2: Bitwise OR with `3` (`b = a | 3`)
* `a` (63) in binary: `0011 1111`
* `3` in binary: `0000 0011`
* **Bitwise OR Operation:**
```text
0011 1111 (a)
| 0000 0011 (3)
-----------
0011 1111 (Result = 63)
```
#### Step 3: Bitwise OR Assignment with `7` (`b |= 7`)
The expression `b |= 7` is equivalent to `b = b | 7`.
* `b` (63) in binary: `0011 1111`
* `7` in binary: `0000 0111`
* **Bitwise OR Operation:**
```text
0011 1111 (b)
| 0000 0111 (7)
-----------
0011 1111 (Result = 63)
```
---
### Key Considerations
1. **Octal Literals:** Always remember that prefixing an integer with `0` in C makes it an octal number. For example, `077` is not seventy-seven; it is sixty-three in decimal.
2. **Common Use Cases:** The bitwise OR operator is frequently used in systems programming to **set specific bits** (flags) to `1` without altering other bits in a register or configuration byte.
YouTip