0

Okay, this maybe a dumb question. But, here it goes.

If i assign a negative value to an unsigned integral type in C++ like "unsigned short a = -1".

The value of a in the above example is set to be 65535 (2^16 - 1). And i know that if i set a value out of range to an unsigned integer, the value set will be the modulo of the number with the max size storable (65536 in this case), can you please explain the math being worked out behind the scenes?

How is (-1) modulo 65536 = 65535 ? Shouldn't it be -1 itself?

Bala Kumar
  • 355
  • 2
  • 4
  • 12

1 Answers1

0

It is a difference of 1 MSB bit. In signed, that 1 bit is used to store the negativity of the number. While in unsigned, that is used to store the value. Its not math that works internally, its basically bit pattern manipulation that makes the difference between the two.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79