The below program tests for Little/Big endian on intel processor. Actually little endian is correct output. First I am casting int to char* and accessing its value without initialization to int *.I am not understanding second part of output. Here int pointer is casted to char *. So why is not int pointer not changed its alignment to char *?
00000000 00000000 00000011 01111111 = 895
0 0 3 127
int main() {
int num = 895;
if(*(char *)&num == 127)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
int *p = (char *)&num ;
if(*p == 127)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
printf("%d\n",*p);
}
o/p
Little-Endian
Big-Endian
895
The first half of your program using this comparison:
looks fine.
The second half of your program contains this assignment:
Which isn’t valid code. You can’t convert pointer types without an explicit cast. In this case, your compiler might be letting you get away with it, but strictly speaking, it’s incorrect. This line should read:
or simply this equivalent statement:
From this example, I’m sure you can see why your second test doesn’t work the way you’d like it to – you’re still operating on the whole
int, not on the single byte you were interested in. If you madepachar *, it would work the way you expected: