Search code examples
pythonctypesbit-fields

How to get the first 11 bits of a 32 bit int with ctypes


How do I get the first 11 bits of a 32 bit int with ctypes?

import ctypes

class Fields(ctypes.Structure):
    _pack_ = 1
    _fields_ = [('a', ctypes.c_uint, 11)]

class BitField(ctypes.Union):
    _pack_ = 1
    _fields_ = [('b', Fields),
                ('raw', ctypes.c_uint)]

bf = BitField()
bf.raw = 0b01010000001000000000000000000001

print('0b{:0>32b}'.format(bf.raw))
print('0b{:0>32b}'.format(bf.b.a))

Result:

0b01010000001000000000000000000001
0b00000000000000000000000000000001

Whereas I wanted

0b01010000001000000000000000000001
0b00000000000000000000001010000001

Solution

  • Another option could be to use

    class Fields(ctypes.Structure):
        _pack_ = 1
        _fields_ = [('x', ctypes.c_uint, 21), ('a', ctypes.c_uint, 11)]