如何:Python 将字节转换为可读的 ASCII/Unicode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14292746/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:59:23  来源:igfitidea点击:

How to : Python Convert Bytes to Readable ASCII/Unicode

python

提问by

this is the bytes i have received,and i would like to convert byte[5] + byte[6] + byte[7] + byte[8] to ASCII readable text.

这是我收到的字节,我想将字节 [5] + 字节 [6] + 字节 [7] + 字节 [8] 转换为 ASCII 可读文本。

s=b'0f0000004e52303947303531363400'

bytes[5]~[8] ASCII/UNICODE is NR09

字节[5]~[8] ASCII/UNICODE 是 NR09

please help thanks.

请帮忙谢谢。

回答by Esailija

bytes.fromhex(s[4*2:8*2].decode("ascii")).decode("ascii")
//'NR09'

Btw, this would be much easier if you didn't use the conversion from Python : convert a hex string

顺便说一句,如果您不使用Python的转换,这会容易得多:convert a hex string

In that question you have:

在那个问题中,你有:

b'\x0f\x00\x00\x00NR09G05164\x00'

So you can do

所以你可以做

c = b'\x0f\x00\x00\x00NR09G05164\x00'
c[4:8].decode("ascii")
//'NR09'

回答by Esailija

rc@xxxxx:~$ python
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s=b'0f0000004e52303947303531363400'
>>> s.decode("hex")[4:8]
'NR09'