Python: convert string to byte array

后端 未结 8 1458
旧时难觅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.

    0 讨论(0)
  • 2020-11-27 05:39

    An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii').

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 05:47

    encode function can help you here, encode returns an encoded version of the string

    In [44]: str = "ABCD"
    
    In [45]: [elem.encode("hex") for elem in str]
    Out[45]: ['41', '42', '43', '44']
    

    or you can use array module

    In [49]: import array
    
    In [50]: print array.array('B', "ABCD")
    array('B', [65, 66, 67, 68])
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 05:55
    s = "ABCD"
    from array import array
    a = array("B", s)
    

    If you want hex:

    print map(hex, a)
    
    0 讨论(0)
提交回复
热议问题