There are several problems with your code.
First, you are doing bit shift operations with signed variables, this may have unexpected results. Use unsigned short
instead of short
to do bit shifting, unless you are sure of what you are doing.
You are explicitly casting a short
to unsigned short
and then storing the result back to a variable of type short
. Not sure what you are expecting to happen here, this is pointless and will prevent nothing.
The issue is related to that. 129 << 8
is 33024
, a value too big to fit in a signed short
. You are accidently lighting the sign bit, causing the number to become negative. You would see that if you printed it as %d
instead of %x
.
Because short
is implicitly promoted to int
when passed as parameter to printf()
, you see the 32-bit version of this negative number, which has its 16 most relevant bits lit in accordance. This is where the leading ffff
come from.
You don't have this problem with long
because even though its signed long
its still large enough to store 33024
without overloading the sign bit.