How to Use Bitwise AND in Embedded C: Syntax and Examples
In Embedded C, use the
& operator to perform a bitwise AND between two integers. It compares each bit of the numbers and returns a new number where bits are set to 1 only if both bits in the operands are 1.Syntax
The bitwise AND operator & is used between two integer values or variables. It compares each bit of the first operand with the corresponding bit of the second operand.
- operand1 & operand2: Returns a value where each bit is 1 only if both bits in operand1 and operand2 are 1.
c
result = operand1 & operand2;
Example
This example shows how to use bitwise AND to check if a specific bit is set in a byte. It also demonstrates combining two numbers with bitwise AND.
c
#include <stdio.h> int main() { unsigned char a = 0b11001100; // binary 204 unsigned char b = 0b10101010; // binary 170 unsigned char result = a & b; printf("a = 0x%X\n", a); printf("b = 0x%X\n", b); printf("a & b = 0x%X\n", result); // Check if bit 3 (counting from 0) is set in a if (a & (1 << 3)) { printf("Bit 3 is set in a.\n"); } else { printf("Bit 3 is not set in a.\n"); } return 0; }
Output
a = 0xCC
b = 0xAA
a & b = 0x88
Bit 3 is set in a.
Common Pitfalls
Common mistakes when using bitwise AND in Embedded C include:
- Using
&instead of logical AND&&when checking conditions. - Not using parentheses when combining bit shifts and bitwise AND, which can cause unexpected results.
- Forgetting that bitwise AND works on bits, not on whole numbers logically.
c
#include <stdio.h> int main() { unsigned char flags = 0b00001000; // Wrong: using bitwise AND instead of logical AND if (flags & 0b00001000) { printf("Bitwise AND used - bit 3 is set.\n"); } // Correct: using logical AND to check if flags is nonzero if (flags && 0b00001000) { printf("Logical AND used - condition true if flags is nonzero.\n"); } return 0; }
Output
Bitwise AND used - bit 3 is set.
Logical AND used - condition true if flags is nonzero.
Quick Reference
Bitwise AND (&) Quick Tips:
- Use
&to mask bits or check if specific bits are set. - Combine with bit shifts
(1 << n)to target bitn. - Remember it operates on bits, not boolean logic.
- Use parentheses to ensure correct order of operations.
Key Takeaways
Use the & operator to perform bitwise AND between two integers in Embedded C.
Bitwise AND returns 1 only where both bits in operands are 1, useful for masking bits.
Use parentheses when combining bit shifts and bitwise AND to avoid errors.
Do not confuse bitwise AND (&) with logical AND (&&) in conditions.
Bitwise AND is essential for checking or clearing specific bits in embedded programming.