c++ memcpy a struct into a byte array -


i have problem copying data of struct bytearray. byte array used pass information thru interface. normal datatypes must use byteswap.

but have struct. when use memcpy, values of struct swapped.

how can copy struct , "correctly" byte array?

memcpy(bytearray, &stdata, sizeof(stdata)); 

stdata has simple integer. 0x0001 stored in byte array 0x1000.

if on x86 architecture machine, integers stored in "little endian" order least significant bytes first. why 0x0001 appear 0x01 0x00 in byte array. long unpack on machine same architecture, work ok, 1 of (many) reasons binary serialization non-trivial.

if need exchange binary data between machines in safe manner, can either decide on standard (e.g. convert binary data little-endian or big-endian; network wire protocols convert big-endian, though many high-performance proprietary systems stick little-endian since today native format on machines) or portable binary file format, such hdf or bson. (these store metadata binary data being stored.) finally, can convert ascii (xml, json). (also, note "big" , "little" aren't choices - "every machine" tall order since haven't been invented yet. :) )

see wikipedia or search "endian" on many examples.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -