Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Endianness manipulation - is there a C library for this?

Tags:

c

endianness

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?

like image 894
Malvineous Avatar asked Apr 03 '10 10:04

Malvineous


People also ask

Is C in little endian?

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.

Does endianness matter in C?

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.

What is big endian in C?

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.

How do I know what endian machine I have?

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”).


2 Answers

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.

like image 198
Dan Story Avatar answered Oct 12 '22 23:10

Dan Story


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.

like image 25
Homer6 Avatar answered Oct 13 '22 00:10

Homer6