5

This should be a pretty simple question but I can't seem to find the answer in my textbook and can't find the right keywords to find it online.

What does it mean when you have a negative sign in front of an unsigned int?

Specifically, if x is an unsigned int equal to 1, what is the bit value of -x?

nalzok
  • 14,965
  • 21
  • 72
  • 139
user1888863
  • 399
  • 2
  • 9
  • 1
    Specifically, the bit value will be the same, regardless of whether the variable is declared as signed or unsigned int. Only the interpretation changes; the underlying binary value does not. – Amadan Apr 11 '16 at 06:12
  • https://repl.it/CEPW/2 – Yosef Weiner Apr 11 '16 at 06:16
  • You get the only number such that `x + (-x) = x - x = 0`, so, the only reasonable result. – harold Apr 11 '16 at 07:22

3 Answers3

10

Per the C standard, arithmetic for unsigned integers is performed modulo 2bit width. So, for a 32-bit integer, the negation will be taken mod 232 = 4294967296.

For a 32-bit number, then, the value you'll get if you negate a number n is going to be 0-n = 4294967296-n. In your specific case, assuming unsigned int is 32 bits wide, you'd get 4294967296-1 = 4294967295 = 0xffffffff (the number with all bits set).


The relevant text in the C standard is in §6.2.5/9:

a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Detail: "is performed modulo 2bit width" is more accurately stated with "is performed modulo (max value + 1)". A difference in the rare case of an unsigned integer containing padding bits. (Something I have never seen.) – chux - Reinstate Monica Apr 11 '16 at 15:50
4

It will overflow in the negative direction, i.e. if your int is 16 bits x will be 65535. The bit value will be 1111111111111111 (16 ones)

If int is 32 bits, x will be 4294967295

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
0

when you apply the "-", the Two's complement of the integer is stored in variable. see here for details

Community
  • 1
  • 1
Afshin
  • 392
  • 2
  • 11
  • 2
    This is really trying to explain it the wrong way arround. Unsigned arithmetic is modulo, and two's complement is the sign representation that uses this simple trick. – Jens Gustedt Apr 11 '16 at 06:44
  • int V1=-1; unsigned int V2=-1; the stored value for both V1 and V2 in memory is 0xffffffff which is the two's complement of 0x00000001. – Afshin Apr 11 '16 at 07:16