from __future__ import print_function from ctypes import * class SubByte(c_ubyte): def __repr__(self): return "%d" % self.value class A(Structure): """A structure containing 2 bitfields of type unsigned byte.""" _fields_ = [("lo", c_ubyte, 5), ("hi", c_ubyte, 3)] class B(Structure): """The same structure containing 2 bitfields, but of type subclass of unsigned byte.""" _fields_ = [("lo", SubByte, 5), ("hi", SubByte, 3)] class TestStruct(Union): """This union allows access via the c_ubyte bit-fields or the SubByte bitfields. """ _fields_ = [("a", A), ("b", B)] t = TestStruct() t.a.hi, t.a.lo = (7, 0) print(t.a.hi, t.a.lo) # prints 7 0 print(t.b.hi, t.b.lo) # prints 224 224 t.a.hi, t.a.lo = (0, 31) print(t.a.hi, t.a.lo) # prints 0 31 print(t.b.hi, t.b.lo) # prints 31 31 t.a.hi, t.a.lo = (7, 31) print(t.a.hi, t.a.lo) # prints 7 31 print(t.b.hi, t.b.lo) # prints 255 255