Question 7
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
char buf[2] = {(char) 0x80, 0x01}; /* big-endian 16-bit value 0x8001 */
int v = (buf[0] << 8) | buf[1];
printf("%d\n", v);
return 0;
}
- A buf[1] must come first
- B char is signed here, so buf[0] is -128; shifting a negative value left is undefined (and sign extension corrupts the result) – read bytes as unsigned char Correct
- C The | should be +
- D There is no bug; it prints 32769
Correct Answer: Option B
Whether plain char is signed depends on the platform; on x86 and Apple ARM it is. Then 0x80 is −128, and -128 << 8 is undefined. Declare the buffer unsigned char (or uint8_t), giving 0x8001 = 32769.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!