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
1
u/Erdnuss2562 Apr 21 '26 edited Apr 21 '26
As mentioned by others, what you're experiencing here is called "integer promotion".
Loosely speaking: C doesn't bother with any types smaller than
intin arithmetics, i.e., allshortandchartypes will be implicitly converted tointbefore any arithmetic is going on. (Literal numbers will always beintor a larger type, if the value doesn't fit inint)This means you can't do "pure" 8-bit arithmetics in C and always need to consider that there's some upper bits - typically 24 of them when you're on a PC where
inthas 32 bits.When you intent to do 8-bit arithmetics, you thus need to check for each operation whether it may "overflow" the 8-bit range and add intermediate casts to
uint8_tto zero out the upper bits. I personally like to do these casts implicitly by splitting down bigger expressions into multiple statements and assigning the intermediate values touint8_tvariables.However, what strikes me most about your example is: Why would you want the
swap_nibbles()function whose purpose is to operate on 8-bit values return auint16_tand not naturallyuint8_t? Because then yourreturnwould include an implicit cast touint8_tand remove those "upper bits" which are remnants of the<<operation.