How to Use Bitwise OR in Embedded C: Syntax and Examples
In Embedded C, use the
| operator to perform a bitwise OR between two integers. This operator compares each bit of the operands and sets the result bit to 1 if either bit is 1, otherwise 0. It is commonly used to set specific bits in hardware registers.Syntax
The bitwise OR operator in Embedded C is represented by |. It takes two integer operands and compares their bits one by one.
- operand1 | operand2: Performs bitwise OR on each bit.
- Each bit in the result is 1 if either corresponding bit in operand1 or operand2 is 1.
- Used to combine flags or set bits without changing others.
c
result = operand1 | operand2;
Example
This example shows how to use bitwise OR to set specific bits in a variable, which is common in embedded programming to control hardware registers.
c
#include <stdio.h> int main() { unsigned char reg = 0x12; // Binary: 00010010 unsigned char mask = 0x05; // Binary: 00000101 // Set bits in reg using bitwise OR reg = reg | mask; printf("Result after OR: 0x%02X\n", reg); return 0; }
Output
Result after OR: 0x17
Common Pitfalls
Common mistakes when using bitwise OR include:
- Using logical OR
||instead of bitwise OR|, which works differently. - Not using unsigned types, which can cause unexpected sign extension.
- Forgetting to assign the result back to a variable, since bitwise OR does not modify operands in place.
c
#include <stdio.h> int main() { unsigned char reg = 0x12; unsigned char mask = 0x05; // Wrong: using logical OR (||) instead of bitwise OR (|) unsigned char wrong = reg || mask; // This will be 1 or 0, not bitwise OR // Correct: unsigned char correct = reg | mask; printf("Wrong result: 0x%02X\n", wrong); printf("Correct result: 0x%02X\n", correct); return 0; }
Output
Wrong result: 0x01
Correct result: 0x17
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| | | Bitwise OR | 0x12 | 0x05 | 0x17 |
| || | Logical OR (not bitwise) | 0x12 || 0x05 | 1 |
| & | Bitwise AND | 0x12 & 0x05 | 0x00 |
| ^ | Bitwise XOR | 0x12 ^ 0x05 | 0x17 |
Key Takeaways
Use the | operator to perform bitwise OR between two integers in Embedded C.
Bitwise OR sets bits to 1 if either operand bit is 1, useful for setting flags.
Avoid confusing bitwise OR (|) with logical OR (||), which behaves differently.
Always assign the result of bitwise OR to a variable; it does not change operands directly.
Use unsigned types to prevent unexpected behavior with bitwise operations.