Bit fields struct assignment unexpected behaviour

后端 未结 2 409
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 2021-01-22 06:02

    Nearly everything about bit-fields is implementation defined. And particularly the order of bits in a unit.

    (C99, 6.7.2.1p10) "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."

    On your implementation, the bits are stored in a unit lsb (least significant bit) first and not msb (most significant bit) first as you would expect.

    What you have is:

    [a1.0] [a2.0] [a2.1] [a2.2] [a2.0] [a3.1] [a4.0] [a4.1] 
       0      0      1      0      1      0      0      1
     bit 0                     -                      bit 7
    
     lsb                       -                      msb
    

    which is 0x94 if you consider the left most bit is the least significant bit.

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