Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing and reading int data into char array

Tags:

c++

arrays

char

I am trying to store two integer value into an char array in C++. Here is the code..

char data[20];
*data = static_cast <char> (time_delay);   //time_delay is of int type
*(data + sizeof(int)) = static_cast<char> (wakeup_code);  //wakeup_code is of int type

Now on the other end of the program, I want to reverse this operation. That is, from this char array, I need to obtain the values of time_delay and wakeup_code.

How can I do that??

Thanks, Nick

P.S: I know this is a stupid way to do this, but trust me its a constraint.

like image 750
Nick Avatar asked Feb 23 '23 09:02

Nick


2 Answers

I think when you write static_cast<char>, that value is converted to a 1-byte char, so if it didn't fit in a char to begin with, you'll lose data.

What I'd do is use *((int*)(data+sizeof(int))) and *((int*)(data+sizeof(int))) for both reading and writing ints to the array.

*((int*)(data+sizeof(int))) = wakeup_code;
....
wakeup_code = *((int*)(data+sizeof(int)));

Alternatively, you might also write:

reinterpret_cast<int*>(data)[0]=time_delay;
reinterpret_cast<int*>(data)[1]=wakeup_code;
like image 116
Vlad Avatar answered Mar 06 '23 12:03

Vlad


If you are working on a PC x86 architecture then there are no alignment problems (except for speed) and you can cast a char * to an int * to do the conversions:

char data[20];
*((int *)data) = first_int;
*((int *)(data+sizeof(int))) = second_int;

and the same syntax can be used for reading from data by just swapping sides of =.

Note however that this code is not portable because there are architectures where an unaligned operation may be not just slow but actually illegal (crash). In those cases probably the nicest approach (that also gives you endianness control in case data is part of a communication protocol between different systems) is to build the integers explicitly in code one char at a time:

first_uint = ((unsigned char)data[0] |
              ((unsigned char)data[1] << 8) |
              ((unsigned char)data[2] << 16) |
              ((unsigned char)data[3] << 24));
data[4] = second_uint & 255;
data[5] = (second_uint >> 8) & 255;
data[6] = (second_uint >> 16) & 255;
data[7] = (second_uint >> 24) & 255;
like image 30
6502 Avatar answered Mar 06 '23 12:03

6502