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.