I need to get 4 bytes from a char array position and set this bits in a int. I have tryed to use some methods, like memcpy(&i, (array+4),sizeof(int)) and direct int i = (int)array[4]. Recently I try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
union data_t{
signedchar ch[4];
int i;
};
data_t data1, data2;
for(int i=0;i<4;i++ ){
array[i] = data1.ch[i]
array[i+4] = data2.ch[i]
}
printf("Values in union: %d and %d\n", data1.i, data2.i);
printf("Values in vector: %d and %d\n", array[0], array[4]);
At this point, data1.i, data2.i and array[0] contains the correct values, but array[4] return a diferent value, in this case seems that it's cutting the first byte.The same problem ocourrs with other forms(memcpy and direct acess to pointer index).
If you simply need to convert a char array to an int just set the location of the int to the location of the char array.
int myInt;
char myArray [4];
&myInt = (int*) myArray;
Seems to me like you want to put ints in to a char array for whatever reason. The easiest way to do this would just be to create an int* and set it to the char*.