Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a int32_t or a int64_t value from a char array

Tags:

c++

arrays

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

like image 422
Miek Avatar asked Jul 27 '12 04:07

Miek


2 Answers

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));
like image 82
Mysticial Avatar answered Sep 21 '22 10:09

Mysticial


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

like image 40
AndersK Avatar answered Sep 22 '22 10:09

AndersK