Introduction
Sometimes you need to know if a specific switch or flag is turned on inside a number. Checking if a bit is set helps you find that out easily.
if (number & (1 << bit_position)) { // bit is set } else { // bit is not set }
int number = 5; // binary 0101 int bit_position = 0; if (number & (1 << bit_position)) { // bit 0 is set }
int number = 8; // binary 1000 int bit_position = 3; if (number & (1 << bit_position)) { // bit 3 is set }
int number = 2; // binary 0010 int bit_position = 1; if (number & (1 << bit_position)) { // bit 1 is set }
#include <stdio.h> int main() { unsigned int number = 13; // binary 1101 int bit_position = 2; if (number & (1 << bit_position)) { printf("Bit %d is set in number %u.\n", bit_position, number); } else { printf("Bit %d is not set in number %u.\n", bit_position, number); } return 0; }
(num & (1 << 3)) != 0 check in embedded C?1 << 3 shifts 1 left by 3 bits, creating a mask with only the 4th bit set (value 8).num & (1 << 3) isolates the 4th bit of num. If this result is not zero, the bit is set.x is set in embedded C?1 << 1, which equals 2.x & (1 << 1) checks if bit 1 is set. If the result is non-zero, the bit is set.unsigned int num = 13; // binary 1101
if (num & (1 << 2))
printf("Bit 2 is set\n");
else
printf("Bit 2 is not set\n");num & (1 << 2) equals 13 & 4 which is 4 (non-zero), so the condition is true.flags is set. What is the error?
unsigned int flags = 0x20;
if (flags & 5 << 1) {
// bit is set
}flags & 5 << 1 is evaluated as flags & (5 << 1) due to operator precedence (<< higher than &).1 << 5 to check bit 5. The current expression does not create the correct mask.status. Write a condition to check if either bit 1 or bit 3 is set. Which of the following is correct?(1 << 1) | (1 << 3) creates a mask with bits 1 and 3 set.status & mask is non-zero to confirm if either bit is set.Pass the test and this pattern moves unknown