Signed short does not accept hex value above 0x7FFF

41 Views Asked by At

When trying to assign a value to a signed short I am unable to assign a value that would wrap around to be a negative value. Take the following assignments:

short a = 0xFF87;  //Cannot be converted to short, should be -121
//short a = 0 - 0xFF87 // doesn't work either
short b = 0x8000;  //Cannot be converted to short, should be -32.768
short c = 0x7FFF;  //Max value I can assign, equals 32.767
short e = -121;    // equals -121

My understanding is that when assigning any values over 0x7FFF the short should roll over to its minimum value of -32.768, and start counting upwards from there. meaning my assignment of 0xFF87 should result in -121. However instead it is giving me an error that the value can not be converted to short.

Windows calculator WORD length showing -121 result

I can feed a hex value prefixed with the minus sign, but this seems weird to me, as my understanding of hex is that you can not prefix it with a negative sign, as this should be coming from the signing bit dictated by the word length used. short d = -0x0079; // equals -121

Even more perculiar to me is that when I inspect the values using the debugger it comes back as FFFFFF87 which is bigger than a short. Negative short shows as 0xFFFFFF87

What should I do so that I can feed a short any value over 0x7FFF and make it wrap to its negative number?

edit: This has been voted as a duplicate of Why should I explicitly surround with "unchecked"? However that questions asks about assigning a value bigger than the data type, which is not the case here, as my value is a valid value for the given data type, given it wraps around as expected.

0

There are 0 best solutions below