Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic cpp14 way to read an int32_t from a char* buffer?

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);
}
like image 247
Pierrot Avatar asked Oct 07 '17 12:10

Pierrot


2 Answers

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

like image 131
n. 1.8e9-where's-my-share m. Avatar answered Oct 21 '22 05:10

n. 1.8e9-where's-my-share m.


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

like image 34
Dúthomhas Avatar answered Oct 21 '22 04:10

Dúthomhas