Python: convert string to byte array

后端 未结 8 1499
旧时难觅i
旧时难觅i 2020-11-27 05:19

Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g.

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 05:54

    This work in both Python 2 and 3:

    >>> bytearray(b'ABCD')
    bytearray(b'ABCD')
    

    Note string started with b.

    To get individual chars:

    >>> print("DEC HEX ASC")
    ... for b in bytearray(b'ABCD'):
    ...     print(b, hex(b), chr(b))
    DEC HEX ASC
    65 0x41 A
    66 0x42 B
    67 0x43 C
    68 0x44 D
    

    Hope this helps

提交回复
热议问题