1. ## Endianess of machine

How can i find out if machine is big/little endian with C... i know big/little endian but dont know how to write program for it. I dont want code but just point me in right direction.

felipe

2. Since endianess works on a byte-level, that means anything larger than one byte will be affected.
So create an integer of >= 2 bytes, fill it with a known value, then check its bytes one by one. Depending on the endianess, they will be appear in different order.

3. By "checking its bytes" as Elysia suggested, it should be accessed one byte at a time after casting an integer to a byte array and looking at those elements. Or using a union to access the data type as integer or bytes.

4. We would 'and' the variable against a known value (something with the high or low bits set e.g. 0x000F) and evaluate the result.

5. Originally Posted by Elysia
Since endianess works on a byte-level, that means anything larger than one byte will be affected.
So create an integer of >= 2 bytes, fill it with a known value, then check its bytes one by one. Depending on the endianess, they will be appear in different order.
If I have like int n=100... then what function is there in the C lib to check its byte one by one.

6. As nonoob explained you can check the bytes of an integer by casting it to a char*.
Code:
```    short data = 0x1020;
char *p = (char *)&data;```
Now p[0] will be the first byte in the representation of data, and p[1] will be the second. If p[0] is 0x20 the machine is little endian, for example.

7. Originally Posted by dwks
As nonoob explained you can check the bytes of an integer by casting it to a char*.
Code:
```    short data = 0x1020;
char *p = (char *)&data;```
Now p[0] will be the first byte in the representation of data, and p[1] will be the second. If p[0] is 0x20 the machine is little endian, for example.
If n is short integer and n=42 then in binary it look like 0000000000101010 as short 2 bytes long on my machine... so in big endian first byte is 00000000 (0) and in litlle endian it is 00101010 (42) correcto?

8. Originally Posted by fsanchez
If n is short integer and n=42 then in binary it look like 0000000000101010 as short 2 bytes long on my machine... so in big endian first byte is 00000000 (0) and in litlle endian it is 00101010 (42) correcto?
Yep!

9. gracias a todos and specially to dwks.