0

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.

Remy
  • 4,843
  • 5
  • 30
  • 60
  • 1
    [Why should I explicitly surround with "unchecked"?](https://stackoverflow.com/q/7823268/555045) gives the way you can do this, annoying as it is. – harold Aug 28 '23 at 19:52
  • @harold thanks for the link, that does indeed "solve" the problem. I can understand needing the `unchecked` in that situation as they are overflowing the max capacity of the value, In my case it feels like it shouldn't be an overflow, as it's a valid 2 byte value. But I guess C# specs disagree with that view – Remy Aug 28 '23 at 20:00

0 Answers0