Byte Array in Python

后端 未结 4 1062
小蘑菇
小蘑菇 2020-12-04 15:23

How can I represent a byte array (like in Java with byte[]) in Python? I\'ll need to send it over the wire with gevent.

byte key[] = {0x13, 0x00, 0x00, 0x00,         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 15:30

    Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

    >>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
    >>> key
    bytearray(b'\x13\x00\x00\x00\x08\x00')
    

    Indexing get and sets the individual bytes

    >>> key[0]
    19
    >>> key[1]=0xff
    >>> key
    bytearray(b'\x13\xff\x00\x00\x08\x00')
    

    and if you need it as a str (or bytes in Python 3), it's as simple as

    >>> bytes(key)
    '\x13\xff\x00\x00\x08\x00'
    

提交回复
热议问题