Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C style strings
#1
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:
    @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')
Reply
#2
Nothing wrong with that, but you can just split() on the null.

>>> b'Hello\x00\xf1\x03'
b'Hello\x00\xf1\x03'
>>> b'Hello\x00\xf1\x03'.split(b'\x00')[0]
b'Hello'
>>> b'No null'.split(b'\x00')[0]
b'No null'
Reply
#3
also, might want to look at: https://www.geeksforgeeks.org/passing-nu...libraries/
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter font style ATARI_LIVE 2 95 Oct-24-2020, 08:22 PM
Last Post: ATARI_LIVE
  Type hinting style and PEP8 hlovatt 2 479 May-07-2020, 08:12 PM
Last Post: hlovatt
  How to generate a log in a list style? wagnergt12 5 463 Apr-22-2020, 12:47 PM
Last Post: buran
  Type hints and style MaxPowers 1 464 Feb-19-2020, 06:56 PM
Last Post: micseydel
  Merging Dictionaries - Optimum Style? adt 5 570 Oct-09-2019, 05:26 PM
Last Post: adt
  Finding multiple strings between the two same strings Slither 1 745 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  lists, strings, and byte strings Skaperen 2 1,831 Mar-02-2018, 02:12 AM
Last Post: Skaperen
  Is this good style? league55 3 1,218 Jan-14-2018, 04:25 PM
Last Post: Gribouillis
  Coding style questions -- variables Luke_Drillbrain 12 4,160 Apr-30-2017, 01:21 AM
Last Post: Luke_Drillbrain
  pdf sms alternating conversation style sdcaliber 4 2,470 Apr-20-2017, 05:20 AM
Last Post: sdcaliber

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020