Using Python struct.unpack with 1 byte variables

How can I use struct.unpack()or some other function available in Python to easily convert a single byte variable into a Python integer? Now this is being done rather roughly:

file = open("telemetry.dat", "rb").read()
magic = file[0]
int(binascii.hexlify(magic), 16)

Is there any other?

+3
source share
4 answers

What about ord(my_byte)?

Or, if the contents of the variable are similar to my_byte == "0xff"or ff you can just doint(my_byte, 16)

If you have streamof hexadecimal digits, you can do:

int_bytes = (int(my_bytes[i:i+2], 16) for i in xrange(0, len(my_bytes), 2) ) 
+7
source

Yes, you can use struct.unpack () with 1 byte variables; see 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

, int int. , - (, int, " > h" "fmt" ).

0

array:

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

; bytearray memoryview ( - Python):

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

struct.unpack() ( ), :

import struct

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

, bytestring, ord() @jsbueno:

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

struct.unpack( 'b', someByte )?

"" - 1- .

The value 0xffis an integer and is already unpacked.

If you find a 4-digit value 0xffin the input file, it is best to use eval()as your input file contains Python code 0xff.

-7
source

Source: https://habr.com/ru/post/1728204/


All Articles