Conversion fron signed to unsigned?

B

Bill

Does a cast from an signed to an unsigned integer always preserve the bit
pattern that represents the value?



signed int a;

unsigned int b;



a = -3;

b = a; /* what happens here ???? */



If int is 16 bits on this system, is b guarantied to get the value 0xFFFD =
65533??





Or should I write the conversion like this to be safe?





b = *((unsigned int *)&a); /* always safe?????? */





What does the standard say about this?
 
R

Richard Bos

Bill said:
Does a cast from an signed to an unsigned integer always preserve the bit
pattern that represents the value?

No. It looks like that because the algorithm which is used to convert
out-of-range values to any unsigned integer type is to take the value
modulo <TYPE>_MAX + 1. This is the same as preserving the bit
representation on 2's complement systems. However, the C Standard does
not require 2's complement: 1's complement and sign-magnitude are also
allowed. They're vanishingly rare, though.
signed int a;
unsigned int b;

a = -3;
b = a; /* what happens here ???? */

If int is 16 bits on this system, is b guarantied to get the value 0xFFFD =
65533??

Yes. Which means that it isn't bit-pattern preserving on anything except
2's complement platforms. That is, it does on the vast majority of
platforms, but not necessarily on all. It _does_ produce a predictable
value, though.
b = *((unsigned int *)&a); /* always safe?????? */

No, unsafe. Or rather, unreliable.

Richard
 
J

Jirka Klaue

Bill:
Does a cast from an signed to an unsigned integer always preserve the bit
pattern that represents the value?

signed int a;
unsigned int b;

a = -3;
b = a; /* what happens here ???? */

b = -3 + UINT_MAX + 1.

BTW: That means, you can get UINT_MAX by assigning -1 to an unsigned int.

unsigned b = -1; /* b == UINT_MAX */
unsigned short c = -1; /* b == USHRT_MAX */

This has nothing to do with bit patterns, the conversion is defined
in terms of values.

Jirka
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top