r/cprogramming • u/cryptofakir • Apr 16 '26
Weird shift expression result
This code outputs what I believe are the wrong results in 3 of the 4 cases. I think the upper 8 bits of the uint16_t should be always 0, because the shifts should occur on uint8_t and only the result should be cast to (uint16_t).
Why am I wrong?
/* Compile: gcc sol.c main.c -o prog && ./prog <1-4> */
/* byte: An 8-bit input
returns: An 8-bit value (returned as uint16_t) where the high 4 bits
and low 4 bits of byte are swapped
Example: swap_nibbles(0xF0) returns 0x0F
*/
uint16_t
void
void
void
void
int
outputs
❯ ./main 1
Result: 0x0F0F
❯ ./main 2
Result: 0x0A2A
❯ ./main 3
Result: 0x0000
❯ ./main 4
Result: 0x0FFF
9
Upvotes
View all comments
Show parent comment
1
u/imaami Apr 18 '26
Coming up 20 years in the near future. I was finding gaps in my understanding way past 10 years. Not convinced I'm done yet.