B
Barry Schwarz
#include<stdio.h>
#define LITTLE_ENDIAN 0
#define BIG_ENDIAN 1
int endian() {
int i = 1;
char *p = (char *)&i;
if (p[0] == 1)
return LITTLE_ENDIAN;
else
return BIG_ENDIAN;
}
int reverseInt (int i) {
unsigned char c1, c2, c3, c4;
if ( endian() == BIG_ENDIAN ) {
return i;
} else {
c1 = i & 255;
c2 = (i >> 8) & 255;
c3 = (i >> 16) & 255;
c4 = (i >> 24) & 255;
return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;
}
}
int main(void)
{
if(endian())
puts("Big Endian Machine");
else
puts("Small Endian Machine");
printf("%d",reverseInt(5));
return 0;
}
I tested it on my PC (On Pentium 4) and this is the output:
Small Endian Machine
83886080.
I am baffled as I was expecting 5 to be printed or is it that I am
missing something completely ?
What you are missing is that the bitwise functions (&, |, <<, >>)
operate on values and not on representations.
Your computation for c1 produces a value of 0x05. Your Pentium is
little-endian and the value passed to reverseInt is stored in memory
as 0x05000000. The value 255 is stored in memory as 0xff000000.
Anding the two produces 0x05000000. The low order byte is then stored
in c1.
In the return statement, the value calculated is 0x05000000 but it is
stored in memory as 0x00000005.
Probably i have completely misunderstood the idea of endianness
No, you just applied it in an inappropriate manner.
Remove del for email