Reading negative values from a file in python

梦想与她 提交于 2019-12-13 01:19:57

问题


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

  • FFFFFFFF, which should be -1, but displays as 4294967295
  • FFFFFFFE, which should be -2, but displays as 4294967294

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.


回答1:


Use the struct module:

import struct

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

Example:

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



回答2:


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



来源:https://stackoverflow.com/questions/10833042/reading-negative-values-from-a-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!