Bit fields struct assignment unexpected behaviour

后端 未结 2 391
天命终不由人
天命终不由人 2021-01-22 05:12

I don\'t know why but the bit fields assignment is not working as expected. Probably is just an stupid thing, but I\'ve not been able to locate the problem.

Any help is

2条回答
  •  故里飘歌
    2021-01-22 05:57

    ASCII art:

      MSB                                LSB
    +----+----+----+----+----+----+----+----+
    |a4.1|a4.0|a3.1|a3.0|a2.2|a2.1|a2.0| a1 |
    +----+----+----+----+----+----+----+----+
    | 1  | 0  | 0  | 1  | 0  | 1  | 0  | 0  |
    +----+----+----+----+----+----+----+----+
    |        0x9        |        0x4        |
    +----+----+----+----+----+----+----+----+
    

    As noted, the behaviour is implementation defined; this is one of two legitimate ways of organizing the data, and seems to be the format chosen on your machine. The alternative behaviour is.

      MSB                                LSB
    +----+----+----+----+----+----+----+----+
    | a1 |a2.2|a2.1|a2.0|a3.1|a3.0|a4.1|a4.0|
    +----+----+----+----+----+----+----+----+
    | 0  | 0  | 1  | 0  | 0  | 1  | 1  | 0  |
    +----+----+----+----+----+----+----+----+
    |        0x2        |        0x6        |
    +----+----+----+----+----+----+----+----+
    

    This was apparently the behaviour you expected.

    Since it is implementation defined, you can look in the manual and find what your compiler does because the compiler must document its behaviour.

    If you have portability to worry about, you will need to think about how you will organize your structure definitions to work the way you need it to work on each platform you use.

提交回复
热议问题