Consider the following C code snippet that uses bitwise OR to set bits in a byte.
unsigned char flags = 0x12; // binary: 00010010
flags = flags | 0x04; // set bit 2
printf("0x%02X", flags);What will be printed?
unsigned char flags = 0x12; flags = flags | 0x04; printf("0x%02X", flags);
Bitwise OR sets bits that are set in either operand.
0x12 is binary 00010010. OR with 0x04 (00000100) sets bit 2, resulting in 00010110 which is 0x16.
Given this C code:
unsigned int status = 0x0F0F;
status |= 0x00F0;
printf("0x%04X", status);What is the output?
unsigned int status = 0x0F0F; status |= 0x00F0; printf("0x%04X", status);
OR operation sets bits that are set in either operand.
0x0F0F OR 0x00F0 sets bits in the middle nibble, resulting in 0x0FFF.
Look at this code snippet:
unsigned char reg = 0x01;
reg = reg | 0x02;
reg = reg & 0xFD;
printf("0x%02X", reg);The programmer wants to set bit 1 and clear bit 2. What is the output and why?
unsigned char reg = 0x01; reg = reg | 0x02; reg = reg & 0xFD; printf("0x%02X", reg);
Check which bit 0xFD clears in binary.
0xFD is 11111101 in binary, which clears bit 1 (second bit), not bit 2. So bit 1 is cleared after setting it, resulting in 0x01 (bits 0 set only).
Which of the following C statements correctly sets bits 0 and 3 of variable flags without changing other bits?
unsigned char flags = 0x00;Remember operator precedence and grouping with parentheses.
Option A uses parentheses to group the OR of shifted bits correctly. Option A lacks parentheses and shifts incorrectly due to precedence. Option A shifts by (0|3)=3 only. Option A uses AND instead of OR.
Given this code:
unsigned char mask = 0x00; mask |= 1 << 1; mask |= 1 << 4; mask |= 1 << 7;
How many bits are set to 1 in mask after these operations?
unsigned char mask = 0x00; mask |= 1 << 1; mask |= 1 << 4; mask |= 1 << 7;
Count how many bits are set by each OR operation.
Each OR sets one distinct bit: bit 1, bit 4, and bit 7. Total bits set = 3.