Skip to content

Instantly share code, notes, and snippets.

@Polda18
Last active October 26, 2024 20:32
Show Gist options
  • Save Polda18/37df2d16c30b9f0732494bd29ebf9214 to your computer and use it in GitHub Desktop.
Save Polda18/37df2d16c30b9f0732494bd29ebf9214 to your computer and use it in GitHub Desktop.
Endianess is important to know. This C function will help you with detecting it.
/*******************************************************************
* Sometimes you need to figure out which endianess the machine
* runs on. C on its own doesn't have any form of endianess
* detection. But using unions can actually be useful to detect
* endianess. Sometimes you need to detect endianess to save
* a binary file in a correct format. Because by default
* the machine uses whichever endianess it operates to save files.
* Which makes the files not transferable between machines that
* use differet endianess. Detecting the endianess is crucial
* so you can swap endianess for file saving AND loading if needed.
*
* Unions are like structs, with the difference being all items
* share the same memory space. Size of the union is determined
* by the largest item in the union. So if you have an int and char
* in a union, the union will take up 4 bytes in memory, because
* int is 4 bytes large, and char is 1 byte large. If it was
* a struct, then it would take up 5 bytes (since struct items
* do not share the same memory space).
*
* Endianess determines how multi-byte values are stored in memory.
* Little endian means the least significant byte will be stored
* earlier in memory than the most significant bit. For big endian,
* it reverses. So if you put number value "1" in an int of a union,
* then what is gonna be stored in the char of a union depends on
* the endianess of the machine. That means we can use the unions
* to our advantage to detect endianess. Let's do that.
*******************************************************************/
#include <stdio.h>
#include <stdbool.h>
union endian {
int i;
char c;
};
bool __is_little_endian() {
union endian det;
det.i = 1;
return (bool) det.c;
}
int main() {
if(__is_little_endian())
fprintf(stdin, "Machine is little endian\n");
else
fprintf(stdin, "Machine is big endian\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment