创建从fi读取正数和负数的方法

2024-07-05 14:52:10 发布

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

我想创建一个可以从4字节的十六进制中读取正值和负值的方法。我现在的方法只适用于正值。在

def readtoint(read):
    keynumber = read[::-1]
    hexoffset=''
    for letter in keynumber:
        temp=hex(ord(letter))[2:]
        if len(temp)==1:
            temp="0"+temp
        hexoffset += "\\x"+temp
    #value = int(hexoffset, 16)
    return struct.unpack('<i', value)[0]

上面的方法目前不起作用,因为我正在尝试使它与负数一起工作。我的程序基本上是从一个文件中读取4个字节,颠倒顺序,转换成十六进制,然后把十六进制转换成整数。对于负值,我被告知使用struct模块,但对于正值似乎不起作用。python中是否有一种方法可以同时处理负值和正值?在

谢谢你!在


Tags: 方法inforread字节valuedeftemp