Consider the following C code that uses the AND operator to mask bits. What will be printed?
unsigned char value = 0xAB; // 10101011 in binary unsigned char mask = 0x0F; // 00001111 in binary unsigned char result = value & mask; printf("0x%X", result);
AND operator keeps bits set only if both bits are 1.
The value 0xAB is 10101011 in binary. The mask 0x0F is 00001111. ANDing them keeps only the last 4 bits: 10101011 & 00001111 = 00001011 which is 0x0B.
Given the code below, what is the printed output?
unsigned int flags = 0xF0F0; // binary: 1111000011110000 unsigned int mask = 0x0FF0; // binary: 0000111111110000 unsigned int masked = flags & mask; printf("0x%X", masked);
AND keeps bits where both are 1.
flags = 0xF0F0 (1111000011110000), mask = 0x0FF0 (0000111111110000). ANDing gives 0000000011110000 = 0x00F0.
What will this C code print?
unsigned char data = 0x5A; // 01011010 unsigned char mask = 0x03; // 00000011 unsigned char result = (data >> 2) & mask; printf("%u", result);
Shift right first, then mask with 0x03.
data >> 2 shifts 01011010 to 00010110 (decimal 22). Mask 0x03 is 00000011. 00010110 & 00000011 = 00000010 = 2.
What does this code print?
unsigned int x = 0x12345678; unsigned int mask = 0x00FF00FF; unsigned int result = x & mask; printf("0x%X", result);
AND keeps bits where mask bits are 1.
x = 0x12345678, mask = 0x00FF00FF. ANDing keeps bytes 2 and 0: 0x00340078.
Consider this code snippet. What will it print?
int x = -42; // Two's complement representation unsigned int mask = 0xFF; unsigned int result = x & mask; printf("0x%X", result);
Masking with 0xFF keeps the lowest 8 bits.
-42 in two's complement (32-bit) is 0xFFFFFFD6. AND with 0xFF keeps 0xD6 (214 decimal).