0

I am currently stuck with this simple bit-shifting problem. The problem is that when I assign a short variable any values, and shift them with << 8, I get 0xffff(2 extra bytes) when I save the result to the 'short' variables. However, for 'long', it is OK. So I am wondering why this would anyhow happen ??


I mean, short isn't supposed to read more than 2 bytes but... it clearly shows that my short values are containing Extra 2 bytes with the value 0xffff.


I'm seeking for your wisdom.. :)

This image describes the problem. Clearly, when the 'sign' bit(15) of 'short' is set to 1 AFTER the bit shift operation, the whole 2 byte ahead turns into 0xffff. This is demonstrated by showing 127(0x7f) passing the test but 0x81 NOT passing the test because when it is shifted, Due to it's upper 8. That causes to set Bit15(sign bit) to '1'. Also, Because 257(0x101) doesn't set the bit 15 after shifting, it turns out to be OK.

Junwoo HWANG
  • 31
  • 1
  • 5
  • Possible duplicate of [Bitshift and integer promotion?](http://stackoverflow.com/questions/3482262/bitshift-and-integer-promotion) – clcto Mar 31 '17 at 00:12

1 Answers1

0

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.

Havenard
  • 27,022
  • 5
  • 36
  • 62
  • Ohhhh.... yeah I figured out that I should do the operation with 'unsigned values' but I didn't know that 0xffff was coming from 'pirntf_parameter'! Thank you for sharing your knowledge! ;) – Junwoo HWANG Mar 31 '17 at 01:20