Python技巧

1. python中struct和union的代码 (参考 Does Python have a bitfield type?)

#!/usr/bin/env python
import ctypes
c_uint8 = ctypes.c_uint8

class Flags_bits(ctypes.Structure):
    _fields_ = [
            ("logout", c_uint8, 1),
            ("userswitch", c_uint8, 1),
            ("suspend", c_uint8, 1),
            ("idle", c_uint8, 1),
        ]

class Flags(ctypes.Union):
    _fields_ = [("b", Flags_bits),
                ("asbyte", c_uint8)]

flags = Flags()
flags.asbyte = 0xc

print(flags.b.idle)
print(flags.b.suspend)
print(flags.b.userswitch)
print(flags.b.logout)



你可能感兴趣的:(Python技巧)