0
0
Embedded Cprogramming~20 mins

Setting a specific bit in a register in Embedded C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Bitwise Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the value of the register after setting bit 3?

Given a register initially set to 0x00, what will be its value after setting bit 3 using the code below?

Embedded C
unsigned char reg = 0x00;
reg |= (1 << 3);
printf("0x%02X", reg);
A0x08
B0x03
C0x10
D0x80
Attempts:
2 left
💡 Hint

Remember that bits are zero-indexed from the right, starting at 0.

Predict Output
intermediate
2:00remaining
What does this code print after setting bit 0 and bit 7?

Consider the following code snippet. What is printed?

Embedded C
unsigned char reg = 0x00;
reg |= (1 << 0);
reg |= (1 << 7);
printf("0x%02X", reg);
A0x80
B0x01
C0x81
D0xFF
Attempts:
2 left
💡 Hint

Bit 0 is the least significant bit, bit 7 is the most significant bit in an 8-bit register.

🔧 Debug
advanced
2:00remaining
Identify the error in setting bit 5

What error does this code produce when trying to set bit 5 of the register?

Embedded C
unsigned char reg = 0x00;
reg = reg | 1 << 5;
printf("0x%02X", reg);
ANo error, prints 0x20
BSyntax error due to missing parentheses
CRuntime error due to operator precedence
DPrints 0x01 instead of 0x20
Attempts:
2 left
💡 Hint

Check operator precedence of bitwise OR and shift operators.

📝 Syntax
advanced
2:00remaining
Which option correctly sets bit 4 without affecting other bits?

Choose the code snippet that sets bit 4 of reg without changing other bits.

Embedded C
unsigned char reg = 0x12; // initial value
Areg |= 1 << 5;
Breg = reg & (1 << 4);
Creg = (1 << 4);
Dreg = reg | (1 << 4);
Attempts:
2 left
💡 Hint

Use bitwise OR to set a bit without clearing others.

🚀 Application
expert
3:00remaining
How many bits are set after this code runs?

Given the code below, how many bits are set to 1 in reg after execution?

Embedded C
unsigned char reg = 0x00;
for (int i = 0; i < 8; i += 2) {
    reg |= (1 << i);
}
printf("%d", __builtin_popcount(reg));
A5
B4
C8
D3
Attempts:
2 left
💡 Hint

Bits set are at positions 0, 2, 4, 6.