So I have the following code:
uint32_t length = 1;
uint8_t buffer[5];
buffer[0] = htonl(length);
std::cout << (uint32_t)*buffer << std::endl;
std::cout << htonl(length) << std::endl;
The second to last line prints out 0, the last line prints out 16777216.....why....?
You are not actually putting the
uint32_t
in the array ofuint8_t
s. Instead, you are placing it inbuffer[0]
. Since length is much larger, only the lowest 8 byte will be stored. And since you've calledhtonl(length)
, the lowest 8 bytes are actually all 0 (at least if your host system is using a different byte-order than the network - and this seems to be the case here).If you actually want to use the first four elements of
buffer
to be used to storelength
, you have to tell the compiler to re-interpret them as auint32_t
.Not that it's a good idea to do, though ..