1

I'm receiving a byte array via serial communication and converting part of the byte array to an integer. The code is as follows:

data = conn.recv(40)
print(data)

command = data[0:7]

if(command == b'FORWARD' and data[7] == 3):
    value = 0
    counter = 8
    while (data[counter] != 4):
        value = value * 10 + int(data[counter] - 48)
        counter = counter + 1    

In short, I unpack the bytearray data starting at location 8 and going until I hit a delimiter of b'\x03'. So I'm unpacking an integer of from 1 to 3 digits, and putting the numeric value into value.

This brute force method works. But is there a more elegant way to do it in Python? I'm new to the language and would like to learn better ways of doing some of these things.

1 Answer 1

1

You can find the delimiter, convert the substring of the bytearray to str and then int. Here's a little function to do that:

def intToDelim( ba, delim ):
    i=ba.find( delim )
    return int(str(ba[0:i]))

which you can invoke with

value = intToDelim( data[8:], b'\x04' )

(or with b'\x03' if that's your delimiter). This works in Python 2.7 and should work with little or no change in Python 3.

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

2 Comments

Thanks for the code. When I tried that, I got the following error: builtins.ValueError occurred Message: invalid literal for int() with base 10: "b'0'"
I guess you're saying return int(str(ba[0:i])) got this ValueError. If so, it sounds like your data (from conn.recv) contains the four ASCII characters b'0' followed by your delim. "b'0'" is not valid Python syntax for a string convertable into an integer. It's not clear to me what syntax your conn.recv is sending you. Do you know from a spec? It looks a bit like it might be trying to express some form of binary literal, in this case simply zero. Your original code would not raise an error, but it would tell you that the value is 49091, which I'm sure is not intended.

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.