If you are reading bytes from a binary file, I suggest to read directly from the file to the integer variable. As followed:
#include <stdio.h>
int main() {
FILE *file = fopen("myFile", "r");
int i;
if (file) {
fread(&i, sizeof(i), 1, file);
printf("%d\n", i);
fclose(file);
}
return (0);
}
But if you cannot get rid of your char array as a source for the conversion, you can use a union to easily perform the conversion:
#include <stdio.h>
#include <string.h>
typedef union u_bytes_to_int_type
{
int value;
char bytes[sizeof(int)];
} u_bytes_to_int_type;
void reverseArray(char *array, unsigned int const size) {
char tmp;
unsigned int reverseIdx;
for (unsigned int i = 0; i < size / 2; ++i) {
reverseIdx = size - 1 - i;
tmp = array[i];
array[i] = array[reverseIdx];
array[reverseIdx] = tmp;
}
}
int main() {
char endiannessIsDifferent = 0; // It's up to you how you determine the value of this variable.
char array[sizeof(int)] = {0x2a, 0, 0, 0};
u_bytes_to_int_type v;
memcpy(v.bytes, array, sizeof(array));
/*
** Will reverse the order of the bytes in case the endianness of
** the source array is different from the one you need.
*/
if (endiannessIsDifferent) {
reverseArray(v.bytes, sizeof(v.bytes));
}
printf("%i\n", v.value);
return (0);
}