python / cpython

The Python programming language
https://www.python.org/
Other
60.06k stars 29.08k forks source link

Please add documentation of the bitfield ordering for ctypes.Structure types #118434

Open TomCulliton opened 2 weeks ago

TomCulliton commented 2 weeks ago

Documentation

The current documentation for ctypes bit fields is very limited and doesn't cover the definition order. AFAICT this is: Little endian - LSB first -> MSB last Big endian - MSB first -> LSB last Native - ??? This is LSB first -> MSB last on x86 but is that just because it's a little endian architecture?

For example:

class BigOnes(BigEndianStructure):
   _pack_ = 1
    _fields_ = (
        ("bit_0", c_uint16, 1),  # MSBit
        ("bit_1", c_uint16, 1),
        ("bit_2", c_uint16, 1),
        ("bit_3", c_uint16, 1),
        ("nibble_1", c_uint16, 4),
        ("nibble_2", c_uint16, 4),
        ("nibble_3", c_uint16, 4),  # LSBit
        ("byte_3", c_uint16, 8),  # MSByte
        ("byte_4", c_uint16, 8),  # LSByte
    )

Versus:

class LittleOnes(LittleEndianStructure):
    _pack_ = 1
    _fields_ = (
        ("bit_0", c_uint16, 1),  # LSBit
        ("bit_1", c_uint16, 1),
        ("bit_2", c_uint16, 1),
        ("bit_3", c_uint16, 1),
        ("nibble_1", c_uint16, 4),
        ("nibble_2", c_uint16, 4),
        ("nibble_3", c_uint16, 4),  # MSBit
        ("byte_3", c_uint16, 8),  # LSByte
        ("byte_4", c_uint16, 8),  # MSByte
    )
TomCulliton commented 2 weeks ago

Note that the field numbering here was only intended to represent the order of definition.