C Programming Basics

uint8_t r = 0x5A;
r |= 0x01;
r &= ~0x10;
r ^= 0x0F;
printf("0x%02X\n", r);

uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above is executed?

  1. A0x44
  2. B0x4F
  3. C0x54
Show answer and explanation

Answer: A. 0x44

0x5A is 0101 1010 in binary. |= 0x01 sets bit 0, giving 0101 1011 (0x5B), and &= ~0x10 clears bit 4, giving 0100 1011 (0x4B). The final ^= 0x0F inverts the lower 4 bits, giving 0100 0100, that is, 0x44. | sets bits, & combined with ~ clears bits, and ^ inverts bits.

  • A. Correct. The value changes 0x5A → 0x5B → 0x4B → 0x44.
  • B. This is the value obtained by mistaking the last ^= for |= and setting the lower 4 bits (0x4B | 0x0F = 0x4F).
  • C. This is the value obtained by skipping &= ~0x10 and leaving bit 4 set (0x5B ^ 0x0F = 0x54).
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?
  2. unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?
  3. uint8_t is an 8-bit unsigned integer type and int is 32 bits. Which of the following is the result when the code above is executed?
  4. int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?
  5. unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?