简体   繁体   中英

c++ memcpy a struct into a byte array

I have a problem with copying data of a struct to my byteArray . This byte array is used to pass information thru an interface. For normal datatypes I must use byteswap .

But now I have a struct. When I use memcpy , the values of the struct are swapped.

How can I copy the struct easily and "correctly" to the byte array?

memcpy(byteArray, &stData, sizeof(stData));

stData has simple integer. 0x0001 will be stored in the byte array as 0x1000 .

If you are on an x86 architecture machine, then integers are stored in "Little Endian" order with the least significant bytes first. That is why 0x0001 will appear as 0x01 0x00 in a byte array. As long as you also unpack on a machine with the same architecture, this will work OK, but this is one of the (many) reasons that binary serialization is non-trivial.

If you need to exchange binary data between machines in a safe manner, then you can either decide on a standard (eg convert all binary data to little-endian or big-endian; network wire protocols generally convert to big-endian, though many high-performance proprietary systems stick with little-endian since today this is the native format on most machines) or look for a portable binary file format, such as HDF or BSON. (These store metadata about the binary data being stored.) Finally, you can convert to ASCII (XML, json). (Also, note that "big" and "little" aren't the only choices - "every machine" is a tall order since they haven't all been invented yet. :) )

See wikipedia or search for "endian" on SO for many examples.

Your problem is that you are in Little Endian end you want to store it as Big endian.

In the standard C hibrary you have functions to do this htons, htonl : host (you little endian machine) to network standard( big endian).

s for 16 bits and l for 32 bits ( http://linux.die.net/man/3/htons )

For 4 bytes integer you can do

#include <arpa/inet.h>
#include <stdint.h>
...
*(uint32_t*)byteArray = htonl((uint32_t)stData);

for 8 bytes int you can use bswap_64 https://www.gnu.org/software/gnulib/manual/html_node/bswap_005f64.html

But it only exists on gnu libc. Otherwise you have to swap manually, there are lot of examples on the web.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM