1

I want to create a method that can read both positive and negative values from a 4 byte hex. The method that I have now works for only positive values.

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]

The above method currently doesn't work because I am trying to make it work with negative numbers. Basically what my program does is it reads 4 bytes from a file, inverts the order, converts it into hex, and then converts the hex into integers. For negative values, I was told to use the struct module but it doesn't seem to work for positive values. Is there a method in python that can handle both negative and positive values?

Thank you!

user1150764
  • 103
  • 1
  • 4
  • 10

1 Answers1

1

Here's a bit of code that will convert 32-bit unsigned to signed:

if value >= 1<<31:
    value -= 1<<32
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622