将Python struct.unpack与1个字节的变量一起使用 [英] Using Python struct.unpack with 1-byte variables
本文介绍了将Python struct.unpack与1个字节的变量一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用struct.unpack()
或Python中提供的其他一些功能轻松地将一个字节变量转换为Python整数?现在,它以一种相当la脚的方式完成:
How can I use struct.unpack()
or some other function available in Python to easily convert one byte variable to a Python integer? Right now, it is done in a rather lame way:
file = open("telemetry.dat", "rb").read()
magic = file[0]
int(binascii.hexlify(magic), 16)
还有另一个吗?
推荐答案
ord(my_byte)
怎么样?
或者变量内容类似于my_byte == "0xff"
或ff
您可以简单地int(my_byte, 16)
Or if the variable content is like my_byte == "0xff"
or ff
you can simply do int(my_byte, 16)
如果您有十六进制数字流,则可以执行以下操作:
If you have a streamof hex digits, you can do:
int_bytes = (int(my_bytes[i:i+2], 16) for i in xrange(0, len(my_bytes), 2) )
这篇关于将Python struct.unpack与1个字节的变量一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文