Welcome to this comprehensive guide on C Bit Manipulation, tailored for embedded systems! In this tutorial, we'll dive deep into the fascinating world of bit manipulation, learning how to work with individual bits in a more efficient way for your embedded projects. 💡
Bit manipulation is the practice of directly accessing, setting, and modifying individual bits (0s and 1s) within a binary number. In C, bit manipulation is performed using bitwise operators. 📝
&): Produces a bit-by-bit logical AND of the two operands.|): Produces a bit-by-bit logical OR of the two operands.^): Produces a bit-by-bit exclusive OR of the two operands.~): Inverts all the bits of the operand.<<): Shifts the bits of the operand to the left by the specified number of positions.>>): Shifts the bits of the operand to the right by the specified number of positions.Let's consider a practical example to better understand bit manipulation. Suppose we have an 8-bit binary number 01011011 and we want to perform various bitwise operations.
#include<stdio.h>
int main() {
unsigned int num = 0b01011011; // Using binary literal
unsigned int mask;
printf("Original number: %d (binary: %o)\n", num, num);
// Bitwise AND
mask = 0b00001111; // Mask for last 4 bits
num &= mask;
printf("Bitwise AND: %d (binary: %o)\n", num, num);
// Bitwise OR
mask = 0b11110000; // Mask for first 4 bits
num |= mask;
printf("Bitwise OR: %d (binary: %o)\n", num, num);
return 0;
}What does the bitwise AND operator (`&`) perform on two operands?
^= 1).Let's implement a function to count the number of set bits (1s) in an integer.
#include<stdio.h>
int countBits(unsigned int num) {
int count = 0;
while (num) {
num &= (num - 1);
count++;
}
return count;
}
int main() {
unsigned int num = 0b11110101;
printf("Number of set bits: %d\n", countBits(num));
return 0;
}What is the purpose of the following code snippet?
Happy learning, and remember to practice, practice, practice! 🤖🚀