Placing uint32_t into array of uint8_t

3.6k views Asked by At

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....?

2

There are 2 answers

2
s3rius On BEST ANSWER

You are not actually putting the uint32_t in the array of uint8_ts. 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 ..

1
David Schwartz On

The second to last line prints out zero coincidentally -- you never stored anything in buffer. You set buffer[0] to a value that wouldn't fit there and left the rest uninitialized.

The last line prints out 16,777,216 because your platform is little-endian and htonl switches to big-endian format, so your 0,0,0,1 becomes 1,0,0,0. That's a one in the 256^3 place, and 1 * 256^3 = 16,777,216.