Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpret *( (char*)&a )

Tags:

c

endianness

I see a way to know the endianness of the platform is this program but I don't understand it

#include <stdio.h>
int main(void)
{
  int a = 1;
  if( *( (char*)&a ) == 1) printf("Little Endian\n");
  else printf("Big Endian\n");
  system("PAUSE");  
  return 0;
}

What does the test do?

like image 859
Niklas Rosencrantz Avatar asked Nov 30 '22 05:11

Niklas Rosencrantz


1 Answers

An int is almost always larger than a byte and often tracks the word size of the architecture. For example, a 32-bit architecture will likely have 32-bit ints. So given typical 32 bit ints, the layout of the 4 bytes might be:

   00000000 00000000 00000000 00000001

or with the least significant byte first:

   00000001 00000000 00000000 00000000

A char* is one byte, so if we cast this address to a char* we'll get the first byte above, either

   00000000

or

   00000001

So by examining the first byte, we can determine the endianness of the architecture.

like image 173
Doug T. Avatar answered Dec 15 '22 00:12

Doug T.