Matriz de bytes em Python
Pergunta
Como posso representar uma matriz de bytes (como em Java com byte []) em Python?Vou precisar enviar por fio com gevent.
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
Solução
No Python 3, usamos o objeto bytes
, também conhecido como str
no 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])
Acho mais conveniente usar o módulo base64
...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
Você também pode usar literais ...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
Outras dicas
Basta usar um bytearray
(Python 2.6 e posterior) que representa uma sequência mutável de bytes
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
A indexação obtém e define os bytes individuais
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
e se você precisar dele como um str
(ou bytes
no Python 3), é tão simples quanto
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
Uma alternativa que também tem a vantagem de registrar facilmente sua saída:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
permite que você faça substituições fáceis como:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
A resposta de Dietrich provavelmente é exatamente o que você precisa para o que descreve, o envio de bytes, mas uma analogia mais próxima ao código que você forneceu, por exemplo, seria usar o tipo bytearray
.
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>