简体   繁体   English

如何在 python 3 中将二进制字节转换为字符串?

[英]How do I convert a binary bytes into string in python 3?

I have a socket receives some binary data sent by the server, the server is written in C++.我有一个socket接收服务器发来的一些二进制数据,服务器写的是C++。 it sends binary data like: 0x10, 0x20, 0x18, 0xAA etc.它发送二进制数据,例如:0x10、0x20、0x18、0xAA 等。

In python 2 I used to be able to receive the data and append it to a string, but now in Python 3 what I received is a byte array, how do I convert that into a string?在 python 2 我曾经能够接收数据和 append 它到一个字符串,但现在在 Python 3 我收到的是一个字节数组,我怎么做?


decode('utf-8') doesn't seem to work, Here is my original code: decode('utf-8') 似乎不起作用,这是我的原始代码:

reply_string = "" while bytes_read < reply_length:
    chunk = s.recv(4096)
    reply_string += chunk.decode('utf-8')

s is a socket, the error I got is: s 是一个套接字,我得到的错误是:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 116: invalid start byte UnicodeDecodeError:“utf-8”编解码器无法解码 position 116 中的字节 0xf7:起始字节无效

The server is written in C++, it doesn't send unicode, it simply read the content of a binary file and send it back to the client, above is the client code.服务端是用 C++ 写的,它不发送 unicode,它只是读取一个二进制文件的内容并发送回客户端,上面是客户端代码。

Ok so assuming the string is in UTF-8 it is as simple as:好的,假设字符串是 UTF-8,它很简单:

try:
    binary_data.decode('utf-8', errors='strict')
except UnicodeError as e:
    # Handle the error here

This code should catch any errors that arise and you can handle them from there.此代码应捕获出现的任何错误,您可以从那里处理它们。

Is there any chance that it might not be using UTF-8?有没有可能不使用 UTF-8? I personally have used socket by just doing incoming_data = s.recv().decode() .我个人只是通过做incoming_data = s.recv().decode()使用套接字。

I'm confused what you are trying to do with the data - if you just want 0x10 , then try doing incoming_data = str(s.recv()) .我很困惑您要对数据做什么-如果您只想要0x10 ,那么请尝试做incoming_data = str(s.recv())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM