How to make int from char[4]? (in C)
c, casting
Solution
This works, but gives different results depending on the size of int, endian and so on..
#include <stdio.h>
int main(int argc, char *argv[])
{
char a[4];
a[0] = 0x76;
a[1] = 0x58;
a[2] = 0x02;
a[3] = 0x00;
printf("%d\n", *((int*)a));
return 0;
}
This is cleaner but you still have endian/size problems.
#include <stdio.h>
typedef union {
char c[4];
int i;
} raw_int;
int main(int argc, char *argv[])
{
raw_int i;
i.c[0] = 0x76;
i.c[1] = 0x58;
i.c[2] = 0x02;
i.c[3] = 0x00;
printf("%d\n", i.i);
return 0;
}
To force a certain endianness, build the `int` manually:
int i = (0x00 << 24) | (0x02 <<< 16) | (0x58 << 8) | (0x76);
printf("%d\n", i);
Problem
I have char a[4] and in it: `a[0] = 0x76` `a[1] = 0x58` `a[2] = 0x02` `a[3] = 0x00` And I want print it as `int`, can you tell me how to do that?