from char arry to int

so here's my problem:
i have a char array:
1
2
3
char start_arry[]={
	0x64, 0x61, 0x74, 0x61, 0x2E, 0x74, 0x78, 0x74,
};

and i want to copy the first 4 bytes to an integer;
1
2
int x=start_arry[0]
int y=start_arry[4]

however, i get a wrong result;
i get:
1
2
x=0x64
y=0x2E

i want the result to be:
1
2
x=0x61746164
y=0x7478742E
How about using unions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
union Char2Int
{
    char c[8];
    unsigned int i[2];
} converter;

char start_arry[]={
    0x64, 0x61, 0x74, 0x61, 0x2E, 0x74, 0x78, 0x74,
};

for (int i = 0; i < 8; ++i)
    converter.c[i] = start_array[i];

int x = converter.i[0];
int y = converter.i[1];


So your goal is to reinterpret the array as two 32-byte values stored in little-endian format.

If you want to be portable, you'd have to be explicit about it:

1
2
3
4
5
6
7
8
int32_t x = start_arry[3] << 24
          | start_arry[2] << 16
          | start_arry[1] << 8
          | start_arry[0];
int32_t y = start_arry[7] << 24
          | start_arry[6] << 16
          | start_arry[5] << 8
          | start_arry[4];


if you are certain your program will only be compiled on little-endian architectures, you can copy:

1
2
3
int32_t x, y;
std::copy(start_arry,   start_arry+4, reinterpret_cast<char*>(&x));
std::copy(start_arry+4, start_arry+8, reinterpret_cast<char*>(&y));


If you are certain your program will only be compiled on little-endian architectures and you aren't bothered by aliasing violations, you can make it even simpler:

1
2
3
int32_t* p = reinterpret_cast<int32_t*>(start_arry);
int32_t x = p[0];
int32_t y = p[1];
Another option is bit-shifting;
1
2
3
4
5
int x = 
    (start_arry[0] << 0)  | 
    (start_arry[1] << 8)  | 
    (start_arry[2] << 16) |
    (start_arry[3] << 24) ;
Last edited on
thanks everyone.
i find this:
Cubbi:
1
2
3
int32_t* p = reinterpret_cast<int32_t*>(start_arry);
int32_t x = p[0];
int32_t y = p[1];

to be the most helping solution which works very well for my purposes.
however, i did not mention that i have a much bigger array, and that sometimes the 4 bytes that i want from the array are not always multiple of 4

1
2
3
char start_arry[]={
	0x64, 0x61, 0x74, 0x61, 0x2E, 0x74, 0x78, 0x74,
};


i want to copy the first 4 bytes from start_array[3] to an integer;

int x=start_arry[3]

however, i get a wrong result;
x=0x61
i want the result to be:
x=0x78742E61
nevermind:
int *p = reinterpret_cast <int*>( start_arry+3 );
Topic archived. No new replies allowed.