I'm writing a program on Linux in C to analyze core files produced from an embedded system. The core files might be little endian (ARM) or big endian (MIPS), and the program to analyze them might be running on a little endian host (x86) or big endian (PowerPC).
By looking at the headers I know whether the core is LE or BE. I'd rather my program not need to know whether the host it runs on is little or big endian, I'd like to use an API to handle it for me. If there is no better option, I guess I'll start relying on #ifdef __BIG_ENDIAN__.
In the Linux kernel we have cpu_to_le32 et al to convert from native byte ordering to little endian, etc. In user space there is htonl et al, which convert from native to big endian but no equivalent for native to little endian that I can find.
Can anyone suggest a suitable API for user space?
Edit: Just to be clear, I'm looking for an API which already knows whether my CPU is big or little endian and swaps byes accordingly. I don't want to have to litter my code with #ifdefs for this. I'm not just looking for code snippets to swap bytes; thank you for those, but that wasn't the point.
You could just write your own (these are based on Apple's routines):
Then you can define conditional macros:
If you're happy with Intel assembler code, you can even do this:
If you treat the file as a byte array, then you control which order you pick the bytes out, and the endian-ness of your CPU actually ends up not mattering.
This is also highly useful in terms of dealing with alignment problems. Your core dump might concievably have unaligned references in it. I know that's highly unlikely, but it could be due to corruption as well. This is another problem that is avoided by treating the file as a byte array.
I used this approach in implementing jhead.
You can use the standard network bytswapping functions in apa/inet.h:
Network byte order is big-endian. So, these functions mean:
Hope this helps.