user963241
user963241

Reputation: 7048

Unsigned to signed conversion in C

Is the following guaranteed to work or implementation defined?

unsigned int a = 4294967294;
signed int b = a;

The value of b is -2 on gcc.

From C99 (§6.3.1.3/3) Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Upvotes: 3

Views: 5030

Answers (2)

ZeZNiQ
ZeZNiQ

Reputation: 718

@ouah's answer tells you that its implementation-defined, but doesn't explain how your implementation yields (-2) specifically. I'll answer that:

1) Your implementation seems to have 32-bit wide int type and 2's complement representation.

2) 4294967294 is (UINT_MAX - 1) = 0xfffffffe.

In your implementation, (UINT_MAX - 1) is converted to signed int as follows:

0xfffffffe is converted as ~(0xfffffffe) + 1 = (1 in binary) + 1 = 10 in binary = 2 in decimal.

Notice that before this conversion the most significant bit was 1 (in 0xfffffffe), so the final number is interpreted to be a negative number after the aforementioned conversion. Thus, you get (-2) as your final answer after the conversion.

Hope this helped.

Upvotes: -2

ouah
ouah

Reputation: 145899

The conversion of a value to signed int is implementation-defined (as you correctly mentioned because of 6.3.1.3p3) . On some systems for example it can be INT_MAX (saturating conversion).

For gcc the implementation behavior is defined here:

The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 6.3.1.3).

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

Upvotes: 10

Related Questions