In general, casting in C is specified in terms of values, not bit patterns - the former will be saved (if possible), but the latter is not necessarily the case. In the case of two views with padding without padding - which is mandatory for fixed integer types - this distinction does not matter, and the cast will indeed be noop.
But even if the conversion from signed to unsigned would change the bit pattern, converting it back again will restore the original value - with the warning that an unconfigured unsigned conversion to a signature is realistic and can raise an overflow signal.
For full portability (which is likely to be redundant), you will need to use the punning function instead of the conversion. This can be done in one of two ways:
Using pointer pointers i.e.
uint32_t u = *(uint32_t*)&x;
with which you should be careful, as this may violate effective input rules (but this is normal for options with signed / unsigned integer types) or through unions, i.e.
uint32_t u = ((union { int32_t i; uint32_t u; }){ .i = x }).u;
which can also be used, for example, to convert from double to uint64_t , which you cannot follow with pointers if you want to avoid undefined behavior.
Christoph Oct 21 '13 at 9:36 on 2013-10-21 09:36
source share