Matriz de bytes en Python
Pregunta
¿Cómo puedo representar una matriz de bytes (como en Java con byte[]) en Python?Tendré que enviarlo por cable con gevent.
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
Solución
En Python 3, usamos el objeto bytes
, también conocido como str
en 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])
Me resulta más conveniente utilizar el módulo base64
...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
También puede utilizar literales ...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
Otros consejos
Sólo usa un bytearray
(Python 2.6 y posterior) que representa una secuencia mutable de bytes
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
La indexación obtiene y establece los bytes individuales.
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
y si lo necesitas como str
(o bytes
en Python 3), es tan simple como
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
Una alternativa que también tiene el beneficio adicional de registrar fácilmente su salida:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
le permite realizar sustituciones sencillas como esta:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
La respuesta de Dietrich es probablemente justo lo que necesita para lo que describe, enviar bytes, pero una analogía más cercana al código que ha proporcionado, por ejemplo, sería usar el tipo bytearray
.
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>