Given a char buffer c containing an int (little endian). How to read it as int32_t?
I wrote this code but it doesn't feel idiomatic cpp.
int32_t v;
char* p = (char*)&v;
for (int i=0; i < 4; i++) {
*(p+i) = *(c+i);
}
The only portable way to copy binary data from a char*
buffer to any other data type is with memcpy
(or an equivalent byte-copying merhod such as std::copy
or one of your own that mimics this behaviour).
memcpy(&my_number, my_buffer, sizeof(my_number));
Of course the buffer should contain correct bits for a given data type. If it originated from memory copying from the same data tyoe on the same machine, then endianness doesn't come into play. Otherwise you have to rearrange the bytes in the required order (either in place or in a temporary buffer), or swap the bytes in a platform-dependent manner in the in the integer itself (maybe with htonl and friends).
There is no magic idiomatic way to handle endianness — endianness is an I/O issue. Either use the htonl()
and ntohl()
functions (available on every system) or just decode them yourself (as you are doing). I recommend writing functions to do it (make your life easier, and verifiable).
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