I've seen a few questions and answers regarding to the endianness of structs, but they were about detecting the endianness of a system, or converting data between the two different endianness.
What I would like to now, however, if there is a way to enforce specific endianness of a given struct. Are there some good compiler directives or other simple solutions besides rewriting the whole thing out of a lot of macros manipulating on bitfields?
A general solution would be nice, but I would be happy with a specific gcc solution as well.
Edit:
Thank you for all the comments pointing out why it's not a good idea to enforce endianness, but in my case that's exactly what I need.
A large amount of data is generated by a specific processor (which will never ever change, it's an embedded system with a custom hardware), and it has to be read by a program (which I am working on) running on an unknown processor. Byte-wise evaluation of the data would be horribly troublesome because it consists of hundreds of different types of structs, which are huge, and deep: most of them have many layers of other huge structs inside.
Changing the software for the embedded processor is out of the question. The source is available, this is why I intend to use the structs from that system instead of starting from scratch and evaluating all the data byte-wise.
This is why I need to tell the compiler which endianness it should use, it doesn't matter how efficient or not will it be.
It does not have to be a real change in endianness. Even if it's just an interface, and physically everything is handled in the processors own endianness, it's perfectly acceptable to me.
some_struct.int_value += 10
- you would have to implement some hackery pokery to get that to work in a specific endianess if your processor doesn't match it. Now imagine doing this everywhere in your code - it'll be a horrible mess. If you are really worried about performance, address this in your marshalling/unmarhsalling code... – Hamamelidaceous__attribute__ ((endianness (BIG_ENDIAN)))
for gcc. Many network protocols uses bigendian (=network byteorder). So protocol sources have lots ofntohs()
,htonl()
, etc calls for making conversions. If there is bit fields in structs, then the code will be even more ugly (Seestruct ip
from "netinet/ip.h"). – Alf