Skip to content

Instantly share code, notes, and snippets.

@bharatkrishna
Last active January 11, 2016 14:31
Show Gist options
  • Save bharatkrishna/3950497 to your computer and use it in GitHub Desktop.
Save bharatkrishna/3950497 to your computer and use it in GitHub Desktop.
Check for Endianess of a Machine
/* Prints if a machine is Big-Endian or Little-Endian */
#include <stdio.h>
#include <stdint.h>
int main()
{
uint32_t num = 0x12345678;
uint8_t *ptr = (uint8_t *) &num;
if (ptr[0] == 0x78)
printf("LITTLE ENDIAN\n");
else
printf("BIG ENDIAN\n");
printf("Bytes in Memory: %x\t%x\t%x\t%x\n",ptr[0],ptr[1],ptr[2],ptr[3]);
printf("Addresses:\t %p\t%p\t%p\t%p\n",&ptr[0],&ptr[1],&ptr[2],&ptr[3]);
return 0;
}
@opendawei
Copy link

there are something wrong in the source code!
Line 10, "if (ptr[0] == 78)" is wrong!!!!! This code should be "if (ptr[0] == 0x78)" !

@bharatkrishna
Copy link
Author

Thanks, I've changed it to 0x78 now. That was an ugly bug indeed :)

@LowLevelMahn
Copy link

you should change the code to

volatile uint8_t *ptr = (uint8_t *) #

or else the evaluation is optmized out at compiletime showing only the compiletime endianess

bool is_little_endian()
{
uint32_t num = 0x12345678;
volatile uint8_t* ptr = (uint8_t *)#
return ptr[0] == 0x78;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment