Daniel Gonzalez
Daniel Gonzalez

Reputation: 63

short not being printed correctly c++

I have this list definition in c++

short list[] = {(short)0x32, (short)0x0F, (short)0xFFFF, (short)0x2A};

And I'm getting this print using prinf:

32 F FFFFFFFF 2A
32 F FFFFFFFF 2A

But when I use different numbers I get the espected result.

short list[] = {(short)0x32, (short)0x0F, (short)0x7FFF, (short)0x2A};

32 F 7FFF 2A
32 F 7FFF 2A 

I'd like to know what's happening. Why is it printing a full integer in the frist place? Thanks.

Upvotes: 0

Views: 136

Answers (1)

Matthias247
Matthias247

Reputation: 10416

I'm guessing you are printing the numbers with printf("%X", value).

In that case you are most likely irritated by sign-extension. The short value 0xFFFF which you have specified equals the decimal value -1. If this is extended/casted to a 32bit integer value you will get the same -1 value, but it's binary representation is 0xFFFFFFFF. This is what you see that gets printed. If you print with printf("%hX", value) you should see the correct value, if you don't have another cast from short to int in between.

Upvotes: 1

Related Questions