将时间打包到位域中

2024-06-07 01:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把当前时间压缩成一个限制性的位模式。你知道吗

前5位是小时,后6位是分钟,后6位是秒,其余的保留

我想出了一个讨厌的位和掩码,然后字符串串联,然后再转换回32位整数。你知道吗

这似乎过于复杂&CPU过于昂贵。有没有更有效、更切题、更优雅的方法?你知道吗


Tags: 方法字符串时间模式整数cpu小时掩码
2条回答

怎么样:

wl = 32
hl = 5
ml = 6
sl = 6

word = hours << (wl - hl) | minutes << (wl-hl-ml) | seconds << (wl-hl-ml-sl)

在其他搜索(http://varx.org/wordpress/2016/02/03/bit-fields-in-python/)和我确定的评论之间:

class TimeBits(ctypes.LittleEndianStructure):
    _fields_ = [
            ("padding", ctypes.c_uint32,15), # 6bits out of 32
            ("seconds", ctypes.c_uint32,6), # 6bits out of 32
            ("minutes", ctypes.c_uint32,6), # 6bits out of 32
            ("hours", ctypes.c_uint32,5), # 5bits out of 32
            ]

class PacketTime(ctypes.Union):
    _fields_ = [("bits", TimeBits),
            ("binary_data",ctypes.c_uint32)
            ]


packtime = PacketTime()
now = datetime.today().timetuple()
packtime.bits.hours = now[3]
packtime.bits.minutes = now[4]
packtime.bits.seconds = now[5]

它为相关字段提供了一个更清晰的结构化设置,尤其是在至少每秒调用一次时。已经为日期和其他位压缩向量创建了类似的结构

相关问题 更多 >