关于二进制转中文的问题。
>>> 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')