Friday, October 07, 2005

Endianess

Endianess refers to the ordering of bytes in a multi-byte number. Big endian refers to the architecture where the most significant byte has the lowest address, while the opposite Little endian, the most significant byte has the highest address.
You can find the endianess of your architecture using the following programming snippets:


int x = 1;
if(*(char *)&x == 1)
printf("little-endian\n");
else printf("big-endian\n");



#define LITTLE_ENDIAN 0
#define BIG_ENDIAN 1

int machineEndianness()
{
short s = 0x0102;
char *p = (char *) &s;
if (p[0] == 0x02) // Lowest address contains the least significant byte
return LITTLE_ENDIAN;
else
return BIG_ENDIAN;
}

Endianess Wiki page for #c on FreeNode.

Tip for MediaWiki Users: mediawiki recognizes hot-keys ( thats php, not ajax) and play with alt+x on your favorite wiki site.

5 comments:

Kannappan said...

same logic wont hold good if one is adamant to use
short s=0x0101; or short s=0x5f05f05f; or so on...

how can he be satiated

Senthil Kumaran said...

agreed.
the first snippet can help then :)

Kannappan said...

isnt both the snippets using the same logic. the difference is just in the notations decimal in the first & hex in the second.

int x=129 or int x=8 or such kind, will leave one as confused.

just trying to see if there is an alternate distinct method of finding endianness

Kannappan said...

ignore the x=129, x=8 example as i havent tested it.

but the logic looks the same.

Senthil Kumaran said...

have not tried the mathematical aspect of it, dude. was just exploreing the #c wiki page, when found the endianess empty, explored how to figure out, tried it, filled up the wiki page.
But you caught this in a different light. :) fine and cool, have not thought about a way to check it yet for any possible input. lemme think. you got any?