With the sort of programs I write (working with raw file data) I often need functions to convert between big and little endian. Usually I write these myself (which is covered by many other posts here) but I'm not that keen on doing this for a number of reasons - the main one being lack of testing. I don't really want to spend ages testing my code in a big endian emulator, and often just omit the code for big endian machines altogether. I also would rather make use of faster functions provided by various compilers, while still keeping my programs cross-platform.
The only things I can find are socket calls like htons() but they require different #include files on each platform, and some GPL code like this, however that particular file, while comprehensive, seems to miss out on some of the high performance functions provided by some compilers.
So, does anyone know of a library (ideally just a .h file) that is well tested and provides a standard set of functions for dealing with endianness across many compilers and platforms?
If machine is little endian then *c will be 1 (because last byte is stored first) and if the machine is big endian then *c will be 0.
Given this explanation, it's clear that endianness doesn't matter with C-style strings. Endianness does matter when you use a type cast that depends on a certain endian being in use.
The big endian byte order means, when the computer writes a word (Multi Byte) into memory, it begins by writing the highest byte to the lowest memory address and continues until it has written the lowest byte to the highest memory address.
If it is little-endian, it would be stored as “01 00 00 00”. The program checks the first byte by dereferencing the cptr pointer. If it equals to 0, it means the processor is big-endian(“00 00 00 01”), If it equals to 1, it means the processor is little-endian (“01 00 00 00”).
There have been a number of proposals for a Boost class (for C++, at least) to do exactly that over the last decade, but none have ever come to fruition, unfortunately.
I'm not aware of any better generalized solution than the htons() function set.
On linux, there's <endian.h>
http://man7.org/linux/man-pages/man3/htole32.3.html
I'd be interested to learn if other operating systems support it as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With