Converting Endianess on a bit field structure

前端 未结 8 666
心在旅途
心在旅途 2021-02-02 03:48

I need to convert a bit-field structure from little-endian to big-endia architecture. What is the best way to do that, as there will be issues in byte boundaries, if I simply sw

8条回答
  •  有刺的猬
    2021-02-02 04:20

    You want to do this between the channel (file, or network) and your structure. My preferred practice is to isolate file I/O from structures by write code that builds the file buffers in a known representation, and matching read code that reverses that transformation.

    Your specific example is particularly difficult to guess at because the bitfields are defined to be unsigned int and sizeof(unsigned int) is particularly non-portable.

    Assuming as a SWAG that sizeof(int)==4 then getting a pointer to the struct and reording the individual bytes probably gets you the answer you want.

    The trick of defining the struct differently for different platforms might work, but in the example you cite there isn't a clean break at byte boundaries, so it is not likely to be possible to produce an equivalent of one platform in the other without splitting one or more of the fields into two pieces.

提交回复
热议问题