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.
str = "ABCD"
I'm trying to get my output to be
array('B', [41, 42, 43, 44])
Is there a straightforward way to accomplish this?
encode function can help you here, encode returns an encoded version of the string
In : str = "ABCD" In : [elem.encode("hex") for elem in str] Out: ['41', '42', '43', '44']
or you can use array module
In : import array In : print array.array('B', "ABCD") array('B', [65, 66, 67, 68])
Just use a
bytearray() which is a list of bytes.
s = "ABCD" b = bytearray() b.extend(s)
s = "ABCD" b = bytearray() b.extend(map(ord, s))
By the way, don't use
str as a variable name since that is builtin.