Consider the following code:
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
uint16_t num = 123;
if (htons(num) == num) {
printf("big endian\n");
} else {
printf("little endian\n");
}
}
I'm wondering whether this code works for checking endianness? I've seen many questions checking it with various pointer/char tricks, but I figure this is simpler. It works off the assumption that if you convert a number to network-byte order (big endian), if it is the same as the original number then you're on a big endian system. Otherwise you're on a little endian system.
Is there a false assumption in this check? Perhaps maybe network-byte order isn't always big endian, though it seems it is standardised to be so.