I recently wanted to assign the content of a 4-bytes array into a 4 byte variable with byte-shifting and logical OR.
I wanted to check if casting directly the array into an int* and getting the value works. I wrote a little test program :
int main(int argc, char** argv) {
int out = 0;
char in[4] = {0xFF,0xFF,0xFF,0xFF};
char *in2 = NULL;
printf("out = %d\n",out);
out = (int)in[0] << 24 | (int)in[1] << 16 | (int)in[2] << 8 | (int)in[3];
printf("out = %d\n",out);
out = 0;
out = *((int*)in);
printf("out = %d\n",out);
in2 = (char*)malloc(4);
for(int i = 0; i < 4; i++)
in2[i] = 0xFF;
out = 0;
// Byte-Shifting & OR
out = (int)in2[0] << 24 | (int)in2[1] << 16 | (int)in2[2] << 8 | (int)in2[3];
printf("out = %d\n",out);
out = 0;
//Direct assignment by recasting
out = *((int*)in2);
printf("out = %d\n",out);
return 0;
}
The output was as expected equals to -1 :
out = 0 out = -1 out = -1 out = -1 out = -1
But I'm worried about memory alignment and the safety of this method : is it safe ? If not, is it due to compiler specification or some kind of undefined behavior ?