Converting Endianess on a bit field structure

前端 未结 8 649
心在旅途
心在旅途 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.

    0 讨论(0)
  • 2021-02-02 04:21

    You could use a 32 bit integer, and extract information out of it using and- and bitshift operators. With that in place, you could simply use htonl (host-to-network, long). Network byte order is big endian.

    This won't be as elegant as a bit-field, but at least you'll know what you have and won't have to worry about the compiler padding your structures.

    0 讨论(0)
提交回复
热议问题