I want to pass a 32-bit signed integer x
through a socket. In order that the receiver knows which byte order to expect, I am calling htonl(x)
before sending. htonl
expects a uint32_t
though and I want to be sure of what happens when I cast my int32_t
to a uint32_t
.
int32_t x = something; uint32_t u = (uint32_t) x;
Is it always the case that the bytes in x
and u
each will be exactly the same? What about casting back:
uint32_t u = something; int32_t x = (int32_t) u;
I realise that negative values cast to large unsigned values but that doesn't matter since I'm just casting back on the other end. However if the cast messes with the actual bytes then I can't be sure casting back will return the same value.
If you mix signed and unsigned int, the signed int will be converted to unsigned (which means a large positive number if the signed int has a negative value).
A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].
Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large.
According to the storage size of each data type, a short integer is represented by 16 bits, while an unsigned integer is represented by 32 bits. With the purpose of using enough computer memory, each data type is used according to the value range of the stored numbers.
In general, casting in C is specified in terms of values, not bit patterns - the former will be preserved (if possible), but the latter not necessarily so. In case of two's complement representations without padding - which is mandatory for the fixed-with integer types - this distinction does not matter and the cast will indeed be a noop.
But even if the conversion from signed to unsigned would have changed the bit pattern, converting it back again would have restored the original value - with the caveat that out-of-range unsigned to signed conversion is implementation-defined and may raise a signal on overflow.
For full portability (which will probably be overkill), you'll need to use type punning instead of conversion. This can be done in one of two ways:
Via pointer casts, ie
uint32_t u = *(uint32_t*)&x;
which you should be careful with as it may violate effective typing rules (but is fine for signed/unsigned variants of integer types) or via unions, ie
uint32_t u = ((union { int32_t i; uint32_t u; }){ .i = x }).u;
which can also be used to eg convert from double
to uint64_t
, which you may not do with pointer casts if you want to avoid undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With