python 将字节数组转换为字符串而不解释字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1916928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert byte array to string without interpreting the bytes?
提问by honeyfuzz
I have a GSM date/time stamp from a PDU encoded SMS it is formatted as so
我有一个来自 PDU 编码的 SMS 的 GSM 日期/时间戳,它的格式是这样的
\x90,\x21,\x51,\x91,\x40,\x33
\x90,\x21,\x51,\x91,\x40,\x33
format yy,mm,dd,hh,mm,ss
格式 yy,mm,dd,hh,mm,ss
I have read them from a binary file into a byte array. I want to convert them to a string but without doing any decoding I want to end up with a string that contains 902151914033. I then need to reverse each 2 characters in the string.
我已将它们从二进制文件读入字节数组。我想将它们转换为字符串但不进行任何解码我想最终得到一个包含 902151914033 的字符串。然后我需要反转字符串中的每 2 个字符。
Can anyone give me some pointers? Many Thanks
谁能给我一些指点?非常感谢
回答by Hamish Grubijan
This should get you started:
这应该让你开始:
>>> s = b'\x90\x21\x51\x91\x40\x33'
>>> lst = [hex(z)[2:] for z in s]
>>> lst
['90', '21', '51', '91', '40', '33']
>>> string = ''.join(hex(z)[3:1:-1] for z in s)
>>> string
'091215190433'
回答by Out of Hanwell
To convert to hex:
要转换为十六进制:
hexdata = ''.join('%02x' % ord(byte) for byte in bindata)
hexdata = ''.join('%02x' % ord(byte) for byte in bindata)
To reverse every other hex character (if I'm understanding correctly):
反转所有其他十六进制字符(如果我理解正确的话):
hexdata = ''.join(('%02x' % ord(byte))[::-1] for byte in bindata)
hexdata = ''.join(('%02x' % ord(byte))[::-1] for byte in bindata)
回答by James
What you mean is that you dowant to do some processing! The unprocessed bytes are most easily represented as characters.
你的意思是你确实想做一些处理!未处理的字节最容易表示为字符。
I think what you want is something along the lines of:
我认为您想要的是以下内容:
r = ''
for num in array:
r += '%2X' % num
return r
Which I'm sure could be wrapped up in an anonymous function, if necessary.
如有必要,我确信可以将其包含在匿名函数中。
回答by charstar
If, in your question, the string you have provided is the literal set of bytes (as ascii) including the \ and , and you wish to strip them out you could use the binascii module and str.replace:
如果在您的问题中,您提供的字符串是包含 \ 和 的字面字节集(ascii),并且您希望将它们去除,则可以使用 binascii 模块和 str.replace:
import binascii
qp = binascii.b2a_qp( bunchabytes )
plainstring = qp.replace( '\x', '' ).replace( ',', '' )
The resultant plainstring will consist of only the digits.
结果纯字符串将仅由数字组成。
回答by tzot
switcher= dict(
(n1*16 + n2, n2*16 + n1)
for n1 in range(16)
for n2 in range(16)
)
def nibble_switcher(bindata):
return type(bindata)(switcher[i] for i in bindata)
# will work with many types, not only bytearray
def nibble_switcher_as_hex_string(bindata):
return ''.join("%02x" % i for i in nibble_switcher(bindata))