0

I've isolated some strange behavior I'm seeing while using ctypes with Python. Clearly I misunderstand some concept and I'm having trouble pinning it down.

Code:

from ctypes import *

class dnpControlPacket(Structure):
    _pack_ = 1
    _fields_ = [
            ("dir", c_bool),
            ("prm", c_bool),
            ("fcb", c_bool),
            ("fcv", c_bool),
            ("fc0", c_bool),
            ("fc1", c_bool),
            ("fc2", c_bool),
            ("fc3", c_bool)
            ]

class ctrlUnion(Union):
    _pack_ = 1
    _fields_ = [
            ("data", dnpControlPacket),
            ("bits", c_bool * 8),
            ("bytes", c_uint8 * 1)
            ]

ctrl = dnpControlPacket(1,1,0,0,0,0,0,0)
cu = ctrlUnion(ctrl)
print("bit format: %s" % [x for x in cu.bits])
print("byte format: %d" % cu.bytes[0])

My goal is to read the data in byte form using the Union (cu). Strangely, the value of the byte is 1 while the individual bits are '11000000'. I'd expect the value of the byte to be 192? i.e.

int('11000000', 2)

Can someone help show me where I'm going wrong with this?

1
  • 2
    You are expecting c_bool to only take 1 bit of space? Commented Apr 16, 2018 at 22:38

1 Answer 1

4

ctypes c_bool is implemented by the C _Bool data type (a.k.a bool since C99). It occupies the smallest addressable space which is typically 1 byte and is quite similar to unsigned char. The difference is that any non-zero assignment is converted to 1 by the compiler. If you want named bits, the closest you get in ctypes is a Bit field

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.