Is there a way to enforce specific endianness for a C or C++ struct?

前端 未结 11 1193
南方客
南方客 2020-12-13 09:24

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 d

11条回答
  •  醉梦人生
    2020-12-13 09:53

    I am not sure if the following can be modified to suit your purposes, but where I work, we have found the following to be quite useful in many cases.

    When endianness is important, we use two different data structures. One is done to represent how it expected to arrive. The other is how we want it to be represented in memory. Conversion routines are then developed to switch between the two.

    The workflow operates thusly ...

    1. Read the data into the raw structure.
    2. Convert to the "raw structure" to the "in memory version"
    3. Operate only on the "in memory version"
    4. When done operating on it, convert the "in memory version" back to the "raw structure" and write it out.

    We find this decoupling useful because (but not limited to) ...

    1. All conversions are located in one place only.
    2. Fewer headaches about memory alignment issues when working with the "in memory version".
    3. It makes porting from one arch to another much easier (fewer endian issues).

    Hopefully this decoupling can be useful to your application too.

提交回复
热议问题