Problem With conversion from char[] to int

Hello,

This is my first question on forum. :)

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{

    signed char 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).

Somebody help-me?

Thanks!


Your union looks correct, however I am not really sure what the rest of your code is trying to do.

What is "array" supposed to be doing?

If you just want to put some bytes into the int, just do this:

1
2
3
4
data_t obj;
obj.ch[0] = 25; //first byte
//...
obj.i; //now you have the int with those bytes 


You don't need a for loop or anything special.
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*.

char myArray [16];

int* intP = (int*)myArray;

for (int i = 0; i < 4; i++)
intP[i] = whatever;
Topic archived. No new replies allowed.