Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide char* into few variables

Tags:

c++

arrays

c

I have some char array: char char[8] which containing for example two ints, on first 4 indexes is first int, and on next 4 indexes there is second int.

char array[8] = {0,0,0,1,0,0,0,1};
int a = array[0-3]; // =1;  
int b = array[4-8]; // =1;

How to cast this array to two int's?

There can be any other type, not necessarily int, but this is only some example:

I know i can copy this array to two char arrays which size will be 4 and then cast each of array to int. But i think this isn't nice, and breaks the principle of clean code.

like image 298
Maciej Wojcik Avatar asked Nov 20 '25 08:11

Maciej Wojcik


1 Answers

If your data has the correct endianness, you can extract blitable types from a byte buffer with memcpy:

int8_t array[8] = {0,0,0,1,0,0,0,1};
int32_t a, b;
memcpy(&a, array + 0, sizeof a);
memcpy(&b, array + 4, sizeof b);

While @Vivek is correct that ntohl can be used to normalize endianness, you have to do that as a second step. Do not play games with pointers as that violates strict aliasing and leads to undefined behavior (in practice, either alignment exceptions or the optimizer discarding large portions of your code as unreachable).

int8_t array[8] = {0,0,0,1,0,0,0,1};
int32_t tmp;
memcpy(&tmp, array + 0, sizeof tmp);
int a = ntohl(tmp);
memcpy(&tmp, array + 4, sizeof tmp);
int b = ntohl(tmp);

Please note that almost all optimizing compilers are smart enough to not call a function when they see memcpy with a small constant count argument.

like image 118
Ben Voigt Avatar answered Nov 22 '25 22:11

Ben Voigt