Question

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
Was it helpful?

Solution

Another option could be to use

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

OTHER TIPS

Bit field implementations vary wildly. If you want to extract specific bits from an integers (instead of interoperating with a C library's struct), you're better off avoiding ctypes entirely and using bitwise operations:

raw = 0b01010000001000000000000000000001
a = raw >> (32 - 11)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top