This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Bitfield Union does not work for bit widths greater than 8 bits
Type: behavior Stage:
Components: ctypes Versions: Python 3.7
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, belopolsky, jschulte, meador.inge, vinay.sajip
Priority: normal Keywords:

Created on 2020-01-21 09:20 by jschulte, last changed 2022-04-11 14:59 by admin.

Files
File name Uploaded Description Edit
python_struct_union_bug.py jschulte, 2020-01-21 09:20
Messages (1)
msg360372 - (view) Author: James (jschulte) Date: 2020-01-21 09:20
Creating a Bitfield from a ctypes union and structure results in unexpected behaviour. It seems when you set the bit-width of a structure field to be greater than 8 bits it results in the subsequent bits being set to zero.



class BitFieldStruct(ctypes.LittleEndianStructure):
    _fields_ = [
        ("long_field", C_UINT32, 29),
        ("short_field_0", C_UINT8, 1),
        ("short_field_1", C_UINT8, 1),
        ("short_field_2", C_UINT8, 1),
    ]


class BitField(ctypes.Union):
    _anonymous_ = ("fields",)
    _fields_ = [
        ("fields", BitFieldStruct),
        ("as32bit", C_UINT32)
    ]

def test_bit_field_union():
    f = BitField()
    f.as32bit = int.from_bytes([255, 255, 255, 255], byteorder='little')

    assert f.long_field == int.from_bytes([255, 255, 255, 31], byteorder='little')
    assert f.short_field_0 == 1
    assert f.short_field_1 == 1
    assert f.short_field_2 == 1

test_bit_field_union()  # this call will fail with an assertion error


Equivalent C which does not fail https://rextester.com/FWV78514

I'm running on Ubuntu 16.04 with python3.6 but I have tested on 3.5, 3.7 and on repl.it with the same behaviour.

It seems as though setting any of the struct fields to be greater than 8 bit width results in any of the following fields being set to zero.
History
Date User Action Args
2022-04-11 14:59:25adminsetgithub: 83588
2020-01-23 07:49:15ammar2setnosy: + vinay.sajip
2020-01-21 16:54:15SilentGhostsetnosy: + amaury.forgeotdarc, belopolsky, meador.inge

versions: - Python 3.5, Python 3.6
2020-01-21 09:20:46jschultecreate