Skip to content
Advertisement

Python ctype Structure/Union Issue

So I am trying to do a bitmap. The data comes from a device as a 32bit number and each bit means something. So I was playing around with ctype Structures and Unions. Trying to do the classic int in and it maps to the individual bits.

JavaScript

and this output. This first line is the 32bit value and the rest are individual bits.

JavaScript

Why are the bits 4 – 31 not being set? and bit 0 – 3 are behaving very weird too

Advertisement

Answer

c_bool is one byte in size and prints 0 for zero and 1 for non-zero. You can see that the size in bytes for the structures are incorrect:

JavaScript

Since Value is a 4-byte integer and all four bytes are non-zero the first four byte-sized c_bool fields in the union print 1.

To specify bit fields correctly, specify a 3rd parameter with the number of bits to use. See Bit fields in structures and unions in the ctypes documentation.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement