Given a register initially set to 0x00, what will be its value after setting bit 3 using the code below?
unsigned char reg = 0x00; reg |= (1 << 3); printf("0x%02X", reg);
Remember that bits are zero-indexed from the right, starting at 0.
Setting bit 3 means turning on the 4th bit from the right (0-based). This corresponds to the value 0x08 in hexadecimal.
Consider the following code snippet. What is printed?
unsigned char reg = 0x00; reg |= (1 << 0); reg |= (1 << 7); printf("0x%02X", reg);
Bit 0 is the least significant bit, bit 7 is the most significant bit in an 8-bit register.
Setting bit 0 adds 0x01, setting bit 7 adds 0x80. Together they form 0x81.
What error does this code produce when trying to set bit 5 of the register?
unsigned char reg = 0x00; reg = reg | 1 << 5; printf("0x%02X", reg);
Check operator precedence of bitwise OR and shift operators.
The bit shift operator has higher precedence than bitwise OR, so 1 << 5 is evaluated first, then ORed with reg. This sets bit 5 correctly.
Choose the code snippet that sets bit 4 of reg without changing other bits.
unsigned char reg = 0x12; // initial valueUse bitwise OR to set a bit without clearing others.
Option D uses OR to set bit 4, preserving other bits. Option D clears bits except bit 4. Option D overwrites reg. Option D sets bit 5, not bit 4.
Given the code below, how many bits are set to 1 in reg after execution?
unsigned char reg = 0x00; for (int i = 0; i < 8; i += 2) { reg |= (1 << i); } printf("%d", __builtin_popcount(reg));
Bits set are at positions 0, 2, 4, 6.
The loop sets bits 0, 2, 4, and 6. That is 4 bits set in total.