Is it possible for an explicit cast of, say, int32_t
to uint32_t
, to alter the bit representation of the value?
For example, given that I have
In the particular case you mention, a conversion from int32_t
to uint32_t
, the bit representation will be the same.
The standard specifically requires intN_t
to be "a signed integer type with width N , no padding bits, and a two’s complement representation". Furthermore, corresponding signed and unsigned types must have the same representation for values within their shared range:
A valid (non-trap) object representation of a signed integer type where the sign bit is zero is a valid object representation of the corresponding unsigned type, and shall represent the same value.
There is one very small possible loophole: in principle, an implementation could, for example, make Correction: This is not possible for a conforming implementation. int32_t
a typedef for int
, and uint32_t
a typedef for unsigned long
, where intand
long are both 32 bits but have different byte orders. But that would only happen in a deliberately perverse implementation.int32_t
and uint32_t
must denote corresponding signed and unsigned types.
The above applies only because you happened to choose int32_t
and uint32_t
for your example, and the standard places very specific restrictions on their representation. (And if an implementation can't meet those restrictions, then it simply won't define int32_t
or uint32_t
.)
More generally, though, signed types are permitted to have one of three representations:
The vast majority of modern systems use two's complement (and have no padding bits). On such systems, signed-to-unsigned conversion with types of the same size generally does not change the bit representation. (The semantics of type conversions are defined in terms of values, but are designed to be convenient for two's complement systems.)
But for a system that uses either sign and magnitude or one's complement, signed-to-unsigned conversion must preserve the value, which means that conversion of a negative value must change the representation.