user1150764
user1150764

Reputation: 103

Reading negative values from a file in python

I am trying to read some negative values from a compressed file that has the hex values:

I know FF should be the marker for - but is there a method in python that can just read the values directly or do I have to make my own method?

Thank you!

Edit: This is for Python 2.6. My program reads from binary data and I am just displaying it in hex to make it simpler. The program simply reads 4 bytes at a time and grabs values from those 4 bytes. It is just some of those values are negative and display the above numbers. I am also hoping someone can explain how Python interprets the binary data into a value so I can write a reverse protocol. Thank you!

I read from hex and convert to values through this method.

def readtoint(read):
    keynumber = read[::-1]
    hexoffset=''
    for letter in keynumber:
        temp=hex(ord(letter))[2:]
        if len(temp)==1:
            temp="0"+temp
        hexoffset += temp
    value = int(hexoffset, 16)
    return value

It grabs 4 bytes, inverses the order, then converts the hex value into a int value. THe values I posted above are inverted already.

Upvotes: 1

Views: 1917

Answers (2)

Martin Vilcans
Martin Vilcans

Reputation: 5718

Use the struct module:

import struct

def readtoint(read):
    return struct.unpack('<i', read)[0]

Example:

>>> readtoint('\xfe\xff\xff\xff')
-2

Upvotes: 6

Maria Zverina
Maria Zverina

Reputation: 11173

Post you file reading code to get the perfect answer. But answer to your question is almost certainly here:

Reading integers from binary file in Python

Upvotes: 0

Related Questions