Python: convert string to byte array

后端 未结 8 1506
旧时难觅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:40

    This works for me (Python 2)

    s = "ABCD"
    b = bytearray(s)
    
    # if you print whole b, it still displays it as if its original string
    print b
    
    # but print first item from the array to see byte value
    print b[0]
    

    Reference: http://www.dotnetperls.com/bytes-python

提交回复
热议问题