An operation I need to perform requires me to get one int32_t value and 2 int64_t values from a char array
the first 4 bytes of the char array contain the int32 value, the next 8 bytes contain the first int64_t value, the the next 8 bytes contain the second. I can't figure out how to get to these values. I have tried;
int32_t firstValue = (int32_t)charArray[0];
int64_t firstValue = (int64_t)charArray[1];
int64_t firstValue = (int64_t)charArray[3];
int32_t *firstArray = reinterpet_cast<int32_t*>(charArray);
int32_t num = firstArray[0];
int64_t *secondArray = reinterpet_cast<int64_t*>(charArray);
int64_t secondNum = secondArray[0];
I'm just grabbing at straws. Any help appreciated
Quick and dirty solution:
int32_t value1 = *(int32_t*)(charArray + 0);
int64_t value2 = *(int64_t*)(charArray + 4);
int64_t value3 = *(int64_t*)(charArray + 12);
Note that this could potentially cause misaligned memory accesses. So it may not always work.
A more robust solution that doesn't violate strict-aliasing and won't have alignment issues:
int32_t value1;
int64_t value2;
int64_t value3;
memcpy(&value1,charArray + 0,sizeof(int32_t));
memcpy(&value2,charArray + 4,sizeof(int64_t));
memcpy(&value3,charArray + 12,sizeof(int64_t));
try this
typedef struct {
int32_t firstValue;
int64_t secondValue;
int64_t thirdValue;
} hd;
hd* p = reinterpret_cast<hd*>(charArray);
now you can access the values e.g. p->firstValue
EDIT: make sure the struct is packed on byte boundaries e.g. with Visual Studio you write #pragma pack(1)
before the struct
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With