First of all, I am using a User Defined function called showBin()
that would print a binary of a integer.As you can see this function checks each bit of a given number from right most position to left most position(MSB to LSB).
Am using a Union
with two members, I have stored 512 in its first
member(short unsigned int a)
,(we know that normally(in Big Endian) the binary of 512 is 0000 0010 0000 0000) and in next step tried to print the values of array c[0]
and c[1]
As my Machine is Little Endian it clearly outputs: 0 2,Now this means that under the hood(in memory) the binary is stored as: 0000 0000 0000 0010
But when i print the value of a
using showBin()
it shows 0000 0010 0000 0000 which is in normal(Big Endian) way, why does this not output in Little Endian way i,e 0000 0000 0000 0010 ????
.even if my computer stores the number in BIG Endian then it should output 2 0 right??
???? Am really Confused..????..can any one Please explain this behavior in simple words.
void showBin(unsigned short int a);
int main()
{
union myun
{
short unsigned int a; //2 bytes
char c[2]; //2 bytes
};
union myun som;
som.a=512;
printf("%hu %hu \n",som.c[0],som.c[1]);
printf("512 in Binary:");showBin(som.a);printf("\n");//Doubt here..
return 0;
}
void showBin(unsigned short int a)
{
int i;
unsigned short int mask=0;
unsigned short int res=0;
for(i=15;i>=0;i--)
{
mask=0;//resetting imp..
mask=mask | (1<<i);
res=a & mask;
(res==0)?printf("0"):printf("1");
}
}
int x = 1;
should makex
equal to 0x01000000 on a 32-bit little-endian machine. Quite clearly, that's not how it works. You can only experience endianness when inspecting data directly in memory; values in variables that are treated as their proper data type will not exhibit any endian-dependent behavior. – unwind