python二进制转中文

您所在的位置:网站首页 二进制翻译成中文 python二进制转中文

python二进制转中文

#python二进制转中文| 来源: 网络整理| 查看: 265

关于二进制转中文的问题。

>>> name = '你好'

>>> name

'你好'

>>> bytes(name,'unicode_escape')

b'\\u4f60\\u597d'

现在我有一段二进制数据,想要转化成中文。

bytes_name = b'\x60\x4f\x7d\x59'

我尝试使用

bytes_name.decode('unicode_escape')

去转化,得到结果

'

O}Y’`,

我应该怎样做才可以得到正确的结果

你好

谢谢!

===========================================================================

谢谢大家,我已找到答案。

那个二进制数据

bytes_name = b'\x60\x4f\x7d\x59'

是用c语言写的另一个程序传送过来的数据。

根据大家的提示,我将

b'\x60\x4f\x7d\x59'

转化成

b'\\u4f60\\u597d'

,然后再

decode('unicode_escape')

即可。

def parse_unicodestring(unicode_bytes,length):

result_bytes = b''

for i in range(0,length,2):

a = hex(unicode_bytes[i])[2:].encode('unicode_escape') if len(hex(unicode_bytes[i])) == 4 else ('0'+hex(unicode_bytes[i])[2:]).encode('unicode_escape')

b = hex(unicode_bytes[i+1])[2:].encode('unicode_escape') if len(hex(unicode_bytes[i+1])) == 4 else ('0'+hex(unicode_bytes[i+1])[2:]).encode('unicode_escape')

result_bytes += b'\u'+b+a

return result_bytes.decode('unicode_escape')

大多数汉字的utf8二进制形态都是三个字节。参照维基百科对utf8编码的描述,将第一个字节的二进制数的前四位掐掉,第二字节的前两位,自己第三字节的前两位掐掉,剩余部分拼起来(总共16位的二进制数值)就是该UTF-8汉字的实际unicode值。转成16进制打印出来就能验证效果了。我曾经亲自实验过。

参考信息 https://en.m.wikipedia.org/wiki/UTF-8

第一次答题。话说我用户名是guoshim,手机端回答。为什么显示为一个叫做murphywuwu的答案?数据串了吗?奇怪了。

你的二进制不对啊。。如下:

>>> name = '你好'

>>> name

'你好'

>>> name.encode()

b'\xe4\xbd\xa0\xe5\xa5\xbd'

>>> bname = name.encode()

>>> bname

b'\xe4\xbd\xa0\xe5\xa5\xbd'

>>> bname.decode()

'你好'

>>>

这是二进制么?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3