Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned and Signed Values in C (Output)

Tags:

c

unsigned

signed

signed int x = -5;
unsigned int y = x;

What is the value of y? How is this so?

like image 433
sambhav jain Avatar asked Sep 08 '10 14:09

sambhav jain


2 Answers

It depends on the maximum value of the unsigned int. Typically, a unsigned int is 32-bit long, so the UINT_MAX is 232 − 1. The C standard (§6.3.1.3/2) requires a signed → unsigned conversion be performed as

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Thus y = x + ((232 − 1) + 1) = 232 − 5 = 4294967291.


In a 2's complement platform, which most implementations are nowadays, y is also the same as 2's complement representation of x.

-5 = ~5 + 1 = 0xFFFFFFFA + 1 = 0xFFFFFFFB = 4294967291.

like image 111
kennytm Avatar answered Nov 02 '22 19:11

kennytm


From the C99 standard:

6.3.1.3 Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 49)

49) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.

So you'll be looking at, effectively, y = x + UINT_MAX + 1.

This just happens to mean that the twos-complement representation is used unchanged as an unsigned integer, which makes this very fast on most modern computers, as they use twos-complement for signed integers.

like image 24
bdonlan Avatar answered Nov 02 '22 20:11

bdonlan