I need efficient way to cast part of array to variable. Let's suppose array is defined as this:
unsigned char bytes[240];
now, I need to get uint32_t
value from somewhere in the array, something like this:
uint32_t * word = reinterpret_cast<uint32_t *>(bytes[4]);
Which I think will get me second word in the array right? My question is, is this safe and portable (windows, linux on x86 & x86_64, os x would be nice, don't care about arm, ia-64 etc).
You should use memcpy
. This portably ensures that there are no alignment or strict aliasing problems. If no copy is needed, compilers are often smart enough to figure this out and directly reference the data in the array:
uint32_t value;
memcpy(&value, &bytes[4], sizeof value);
//Modify value:
//...
//Copy back to array:
memcpy(&bytes[4], &value, sizeof value);