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 of uint8_t
s. Instead, you are placing it in buffer[0]
. Since length is much larger, only the lowest 8 byte will be stored. And since you've called htonl(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 store length
, you have to tell the compiler to re-interpret them as a uint32_t
.
uint32_t length = 1;
uint8_t buffer[5];
(uint32_t&)*buffer = htonl(length);
std::cout << (uint32_t)*buffer << std::endl;
std::cout << htonl(length) << std::endl;
Not that it's a good idea to do, though ..