-2

I have a socket receives some binary data sent by the server, the server is written in C++. it sends binary data like: 0x10, 0x20, 0x18, 0xAA etc.

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?


decode('utf-8') doesn't seem to work, Here is my original code:

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:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 116: invalid start byte

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.

3
  • 3
    Why do you want a string? A bytearray seems semantically appropriate. The data you're receiving isn't text. Commented Jan 17, 2019 at 20:18
  • Do you literally just want 0x10 0x20 ... as text? Commented Jan 17, 2019 at 20:21
  • 1
    The Python 2 str type and the Python 3 bytes type behave very similarly. If your code worked in Python 2.7, I would expect it to continue working in 3.X, no type conversion required. Can you provide a minimal reproducible example that demonstrates the problem? Commented Jan 17, 2019 at 20:26

2 Answers 2

0

Ok so assuming the string is in UTF-8 it is as simple as:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Is there any chance that it might not be using UTF-8? I personally have used socket by just doing 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()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.