Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    unsigned char c = 0xAB;
    printf("%d", c & 0x0F);
    return 0;
}

  • A.11
  • B.171
  • C.10
  • D.160

Answer: B

Correct answer: 11

0xAB is 10101011 in binary, and 0x0F is 00001111. A mask of four low ones ANDed against a value keeps that value’s low four bits and zeroes everything above them:

  0xAB = 1 0 1 0 1 0 1 1
  0x0F = 0 0 0 0 1 1 1 1
  ---------------------
     & = 0 0 0 0 1 0 1 1

The result 00001011 is 0x0B, or 11 in decimal.

The shortcut worth learning is that one hexadecimal digit is exactly four bits, so masking with 0x0F simply keeps the last hex digit - the B of 0xAB, which is 11. By the same reasoning c >> 4 would give the other digit, 10. The distractor 171 is 0xAB itself, unmasked.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.