4
votes

Is there a set of C library functions (or non-library functions collected somewhere) which allow conversion of byte-array data into integers with various conversions (big-endian data, little-endian data, one's complement signing, two's complement signing, et cetera), taking into account the machine's own endianness?

Thanks!

2
Could you explain what htonl() and friends + casting does not solve for your problem? - Mel
htonl() does not strictly define an endedness for either its input or its output. If there is a strictly-defined standard for it, do let me know. Casting is not a workable solution since conversions between signed and unsigned data are architecture-dependent whereas data may be moved between architectures. In my mind I see a function called as such: convert_data(buffer, BIG_ENDIAN | TWO_COMPLEMENT). - Richard
So you have an undefined transport mechanism for data (thus htonl won't help), but the data format/container tells you how it was stored and you're looking for a library that can convert it. Don't know of any. Was thinking of xparam for a bit, but it looks like you already have a container/serialization in place. - Mel
Yes, that's an a fairly accurate description. The data is stored in files by third-parties and the format cannot be changed by me, may vary, and is specified by the third-party. - Richard

2 Answers

1
votes

This comes close, although I don't think it will handle one's complement vs. two's complement. You might be able to add that. http://code.google.com/p/protobuf-c/

0
votes

As I understand, you are trying to get an unequivocal BIG_ENDIAN (or LITTLE_ENDIAN) number, without necessarily knowing what your current host's convention is. This should be possible.

To my best understanding, by convention "network byte order" is always BIG_ENDIAN. So you can call htonx(), then you know it is BIG_ENDIAN. Then if you want LITTLE_ENDIAN, you can manually transpose the bytes in your own code. The result should be your own toBigEndian() or toLittleEndian() functions.

The 2's complement part of the question does not admit of the same thing, since it is entirely a matter of convention. Say the number is two bytes long - almost every combination of 16 bit values is both a valid 1's complement number, and also a valid 2's complement number. The "correct" value depends entirely on the interpretation that was put on it by the code which wrote that value.