May-16-2020, 06:31 AM
(This post was last modified: May-16-2020, 06:31 AM by deanhystad.)
I have a Python program that communicates with a C program over a socket connection. The C program sends a "message" which contains floats and ints and some strings as binary data. Strings are a fixed number of bytes in the message even though the length of the string sent may differ, The C program is rather sloppy about sending strings, so the bytes for 'Hello' may look like b'Hello\x00\xf1\x03' when received by the Python program.
Is there a an existing solution for converting this into a Python string that only contains the decoded bytes[0:4]? Currently I am doing this:
Is there a an existing solution for converting this into a Python string that only contains the decoded bytes[0:4]? Currently I am doing this:
@staticmethod def unpackstr(buf, size=None): """Unpack string from buf with max length of size""" if size is None: size = len(buf) length = buf.find(b'\00') if length < 0: length = size else: length = min(length, size) return buf[:length].decode('UTF-8')