Skip to content

Instantly share code, notes, and snippets.

@kindlychung
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kindlychung/7c861b0a30115707468b to your computer and use it in GitHub Desktop.
Save kindlychung/7c861b0a30115707468b to your computer and use it in GitHub Desktop.
check whether the system is little or big endian
#include <stdio.h>
int main(int argc, const char *argv[])
{
int x = 1;
char *y = (char*)&x;
printf("If next line prints 1, then it's little-endian.\n")
printf("%c\n", (*y)+48);
return 0;
}
// Suppose we are on a 32-bit machine.
//
// If it is little endian, the x in the memory will be something like:
//
// higher memory
// ----->
// +----+----+----+----+
// |0x01|0x00|0x00|0x00|
// +----+----+----+----+
// A
// |
// &x
// so (char*)(*x) == 1, and *y+48 == '1'.
//
// If it is big endian, it will be:
//
// +----+----+----+----+
// |0x00|0x00|0x00|0x01|
// +----+----+----+----+
// A
// |
// &x
// so this one will be '0'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment