Python: convert string to byte array

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

    Just use a bytearray() which is a list of bytes.

    Python2:

    s = "ABCD"
    b = bytearray()
    b.extend(s)
    

    Python3:

    s = "ABCD"
    b = bytearray()
    b.extend(map(ord, s))
    

    By the way, don't use str as a variable name since that is builtin.

提交回复
热议问题