Domanda
Come posso rappresentare un array di byte (come in Java con byte []) in Python?Dovrò inviarlo via cavo con gevent.
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
Soluzione
In Python 3, usiamo l'oggetto bytes
, noto anche come str
in Python 2.
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
Trovo più conveniente utilizzare il modulo base64
...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
Puoi anche usare letterali ...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
Altri suggerimenti
Usa semplicemente un bytearray
(Python 2.6 e versioni successive) che rappresenta una sequenza mutabile di byte
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
L'indicizzazione ottiene e imposta i singoli byte
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
e se ne hai bisogno come str
(o bytes
in Python 3), è semplice come
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
Un'alternativa che ha anche l'ulteriore vantaggio di registrare facilmente il suo output:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
ti consente di eseguire semplici sostituzioni in questo modo:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
La risposta di Dietrich è probabilmente proprio ciò di cui hai bisogno per ciò che descrivi, inviando byte, ma un analogo più vicino al codice che hai fornito, ad esempio, sarebbe usare il tipo bytearray
.
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>