Come convertire i byte in numeri interi in Python 2.7 e 3.x
Il tipo di dati Bytes ha un valore che va da 0 a 255 (da 0x00 a 0xFF). Un byte ha 8 bit, per questo il suo valore massimo è 0xFF. In alcune circostanze, è necessario convertire i byte o l’array di byte in interi per l’ulteriore elaborazione dei dati. Questo breve articolo introduce come fare la conversione da byte a interi.
Tipo di dati Python 2.7 byte
Nella versione Python 2.7 non c’è un tipo di dati “byte” integrato. La parola chiave byte è identica a str.
>>> bytes is str
True
bytearray is used to define a bytes or byte array object.
>>> byteExample1 = bytearray([1])
>>> byteExample1
bytearray(b'\x01')
>>> byteExample2 = bytearray([1,2,3])
>>> byteExample2
bytearray(b'\x01\x02\x03')
Convertire i byte in numeri interi in Python 2.7
Il modulo interno di Python struct potrebbe convertire dati binari (byte) in interi. Potrebbe convertire byte o effettivamente stringhe in Python 2.7 e interi in modo bidirezionale.
struct.unpack(fmt, string)
# Convert the string according to the given format `fmt` to integers. The result is a tuple even if there is only one item inside.
Esempi di struct
import struct
testBytes = b"\x00\x01\x00\x02"
testResult = struct.unpack(">HH", testBytes)
print testResult
(1, 2)
La stringa di formato >HH contiene due parti.
>indica che i dati binari sonobig-endian, o in altre parole, i dati sono ordinati da big end (bit più significativo). Per esempio,\x00\0x1significa che\x00è un byte alto e\x01è un byte basso.HHsignifica che ci sono due oggetti di tipoHnella stringa di byte.Hrappresentaunsigned shortintero che prende 2 byte.
Si possono ottenere risultati diversi dalla stessa stringa se il formato dati assegnato è diverso.
>>> testResult = struct.unpack('<HH', testBytes)
>>> testResult
(256, 512)
Qui, < indica che l’indiana è little-endian. Quindi \x00\x01 diventa 00+1*256 = 256, non 0*256+1 = 1.
>>> testResult = struct.unpack('<BBBB', testBytes)
>>> testResult
(0, 1, 0, 2)
B significa che i dati sono unsigned char che prendono 1 byte. Quindi, \x00\x01\x00\x00\x02 sarà convertito in 4 valori di unsigned char, non più 2 valori di unsigned short.
>>> testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
error: unpack requires a string argument of length 3
Si potrebbe controllare il documento ufficiale del modulo struct per ottenere maggiori informazioni di stringhe di formato.
Python 3 Bytes Tipo di dati
bytes è un tipo di dati integrato in Python 3, quindi, si possono definire i byte direttamente usando la parola chiave bytes.
>>> testByte = bytes(18)
>>> type(testByte)
<class 'bytes'>
Si potrebbe anche definire direttamente un array di byte o di byte come segue
>>> testBytes = b'\x01\x21\31\41'
>>> type(testBytes)
<class 'bytes'>
Convertire i byte in numeri interi in Python 3
Oltre al modulo struct come già introdotto in Python 2.7, si potrebbe anche usare il nuovo metodo integer integrato in Python 3 per fare le conversioni da byte a integers, cioè il metodo int.from_bytes().
int.from_bytes() Esempi
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big')
61712
L’opzione byteorder è simile a struct.unpack() format byte order definition.
int.from_bytes() ha una terza opzione signed per assegnare il tipo di numero intero da signed o unsigned.
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
-3824
Usare [] Quando Bytes è unsigned chart
Se il formato dei dati ha il formato di unsigned chart che contiene un solo byte, si può usare direttamente l’indice degli oggetti per accedere e ottenere anche il numero intero dei dati.
>>> testBytes = b'\xF1\x10'
>>> testBytes[0]
241
>>> testBytes[1]
16
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook