c++ - casting array to variable -
i need efficient way cast part of array variable. let's suppose array defined this:
unsigned char bytes[240];
now, need uint32_t
value somewhere in array, this:
uint32_t * word = reinterpret_cast<uint32_t *>(bytes[4]);
which think me second word in array right? question is, safe , portable (windows, linux on x86 & x86_64, os x nice, don't care arm, ia-64 etc).
you should use memcpy
. portably ensures there no alignment or strict aliasing problems. if no copy needed, compilers smart enough figure out , directly reference data in array:
uint32_t value; memcpy(&value, &bytes[4], sizeof value); //modify value: //... //copy array: memcpy(&bytes[4], &value, sizeof value);
Comments
Post a Comment