问题描述
我正在使用GitHub上的此函数从Python的HID流中读取一些数据。 h.read(64)
def decode_bytes(byte_1,byte_2,byte_3,byte_4):
bytes_reversed_and_concatenated = byte_4 * (16 ** 6) + byte_3 * (16 ** 4) + byte_2 * (16 ** 2) + byte_1
bytes_hex = hex(bytes_reversed_and_concatenated)[2:]
bytes_decimal = str(round(struct.unpack('!f',bytes.fromhex(bytes_hex))[0],1))
return bytes_decimal
该函数将流中的四个字节(以十六进制值作为整数)转换为Python浮点值,并以字符串形式返回。我读过C结构浮点表示形式占用四个字节,因此我想这解释了该函数需要四个字节作为输入。但是除此之外,我对该功能的工作方式和原因非常空白。
我有两个问题:
首先,我非常想更好地了解该函数的工作原理。为什么它会反转字节顺序,而16 ** 6、16 ** 4等又是什么呢?我很难弄清楚Python中的功能。
第二,我想撤消该功能。这意味着我希望能够提供一个浮点数作为输入,并列出四个整数十六进制值的列表,我可以通过HID接口将其写回。但是我不知道从哪里开始。
我希望获得正确方向的一些指导。非常感谢您的帮助。
解决方法
所以@ user2357112的评论帮助我弄清楚了所有内容。现在,工作且简单得多的功能如下所示:
def compute_leap_years(start_year,start_month,start_day,end_year,end_month,end_day):
if calendar.isleap(start_year) and (start_month >= 3 and not(bool(start_month == 2 and start_day == 29))):
start_year = start_year + 1
if calendar.isleap(end_year) and (end_month <= 2 and not(bool(end_month == 2 and end_day == 29))):
end_year = end_year - 1
days = calendar.leapdays(start_year,end_year)
return days
如果我想将浮点数包装为字节数组,请执行以下操作:
def decode_bytes(byte_1,byte_2,byte_3,byte_4):
return_value = struct.unpack('<f',bytes([byte_1,byte_4]))
return str(round(return_value[0],1))
在此过程中,我还对Endianness有所了解。谢谢。