开发者

Using Python struct.unpack with 1-byte variables

开发者_JS百科

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)

Is there another?


how about ord(my_byte) ?

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) ) 


Yes, you can use struct.unpack() with 1-Byte variables; see the example below:

import struct
my_byte = b'\x07';
my_int = struct.unpack('>H', b'\x00' + my_byte)[0]

print type(my_int)
print my_int

The above example assumes your int is an unsigned int. Take a look at the Format Characters section of the documentation if you need something different (e.g. a signed int, which would be '>h' for the 'fmt' parameter of the unpack function call).


An efficient way to interpret each byte from a file as an integer is to use array module:

import os
from array import array

a = array("B") # interpret each byte as unsigned integer [0, 255]
with open("telemetry.dat", "rb") as file:
    a.fromfile(file, os.path.getsize(file.name))

If you already have data as a bytestring; you could use bytearray or memoryview (the latter behaves differently on different Python versions):

data = b"\xff\x64d"
# a.fromstring(data)
b = bytearray(data)
print(b[0]) # -> 255

Here's the corresponding struct.unpack() analog (more generic) that returns a tuple:

import struct

data = b"\xff\x64d"
t = struct.unpack(len(data)*"B", data)
print(t[-1]) # -> 100

For a single byte represented as a bytestring, you could use ord() suggested by @jsbueno:

i = ord(b"d") # -> 100


Are you asking about struct.unpack( 'b', someByte )?

A "byte" is a 1-character string.

The value 0xff is an integer, and already unpacked.

If you're finding the 4-character value 0xff in an input file, you're best served by eval() since your input file contains Python code, 0xff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜