简体   繁体   中英

How can I convert a byte array to an integer more elegantly in Python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM