C program to test small and large endian

Possible duplicate:
C Defining a macro to define a large finite or small machine

int main() { int x = 1; char *y = (char*)&x; printf("%c\n",*y+48); } 

If it is a little endian, it will print 1. If it is a big endian, it will print 0. Is this correct? Or will setting char * to int x always point to the least significant bit, regardless of its nature?

+44
c endianness byte
09 Oct
source share
4 answers

In short, yes.

Suppose we are on a 32-bit machine.

If it's a little endian, x in memory would look something like this:

  higher memory -----> +----+----+----+----+ |0x01|0x00|0x00|0x00| +----+----+----+----+ A | &x 

so (char*)(*x) == 1 and *y+48 == '1' .

If this is the big end, it will be:

  +----+----+----+----+ |0x00|0x00|0x00|0x01| +----+----+----+----+ A | &x 

so it will be '0' .

+71
Oct 09
source share
β€” -

The following is done.

 unsigned int x = 1; printf ("%d", (int) (((char *)&x)[0])); 

And setting &x to char * will allow you to access individual bytes of an integer, and the byte order will depend on the nature of the system.

+18
09 Oct '12 at 3:24
source share

This is a great endian test from the configure script:

 #include <inttypes.h> int main(int argc, char ** argv){ volatile uint32_t i=0x01234567; // return 0 for big endian, 1 for little endian. return (*((uint8_t*)(&i))) == 0x67; } 
+12
09 Oct
source share

Thought I knew what I read about it in the standard; but can't find him. Watching. Old; response header; not Q-tex; P:




The following program will determine that:

 #include <stdio.h> #include <stdint.h> int is_big_endian(void) { union { uint32_t i; char c[4]; } e = { 0x01000000 }; return ec[0]; } int main(void) { printf("System is %s-endian.\n", is_big_endian() ? "big" : "little"); return 0; } 

You also have this approach ; from Quake II:

 byte swaptest[2] = {1,0}; if ( *(short *)swaptest == 1) { bigendien = false; 

And !is_big_endian() not 100% smaller since it can be mixed / medium.

Believe me, this can be verified using the same approach, only the change value from 0x01000000 to ie 0x01020304 , giving:

 switch(ec[0]) { case 0x01: BIG case 0x02: MIX default: LITTLE 

But not quite sure about it ...

+7
09 Oct
source share



All Articles