Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top