简体   繁体   中英

Read Serial and Convert HEX to DEC

Read Serial

Using PySerial the following program was created:

import serial


class comunicacao():
    def __init__(self, porta, baud):
        s = serial.Serial(porta, baud)
        data = s.read(18)
        data = data
        print("Data: ", (data))

comunicacao('COM7', 57600)

It is receiving the number 10000 in decimal for tests, and the print output is: Data: b'\\x020000000000002710\\x03'

Because 2710 in HEX is 10000 in DEC.

Conversion

So trying to convert with the following ways:

  • print("Data: ", int(data, 16)) gives teh error:

print("Data: ", int(data, 16))

ValueError: invalid literal for int() with base 16: b'\\x020000000000002710\\x03'

  • With data = s.read(18).decode() the print output is Data: 0000000000002710 and trying to convert with int() gives the error:

print("Data: ", int(data, 16))

ValueError: invalid literal for int() with base 16: '\\x020000000000002710\\x03'

  • data = data.lstrip("0") with data = s.read(18).decode() didn't strip the leading zeroes.
  • And data = data.lstrip("0") with data = s.read(18) gives the error:

print("Data: ", (data.lstrip("0")))

TypeError: a bytes-like object is required, not 'str'

Question

How to convert this data type (I think it is as ASCII, but is a HEX number) to DEC?

What about this:

data = '\x020000000000002710\x03'
# If we say that "\x02" opens an hexadecimal representation of an integer,
# and that "\x03" ends it, then for any number of ints in hex form in data, do:
converted = [int(x, 16) for x in data.replace("\x02", "").split("\x03") if x]
print(converted)
print(converted[0])

You get the list of all numbers you read from the port. What this code does is that it removes the \\x02 character so not to confuse the int() and then splits data by \\x03. Then it converts each element using the int(x, 16). Using the classic way with added try statement would be more robust, if you expect some other data to be mixed in:

converted = []
for x in data.replace("\x02", "").split("\x03"):
    try:
        converted.append(int(x, 16))
    except: pass

If "\\x03" is not the int separator, you can use \\x02 as one and combine the slicing to extract the number of needed digits.

If "\\x03" is still the hexnum terminator, but the numbers do not follow eachother then use something like this:

data = '\x020000000000002710\x03blahblah\x0200ff\x03mmmm'
converted = []
for x in data.split("\x02"):
    end = x.find("\x03")
    if end==-1: continue
    x = x[:end]
    try:
        converted.append(int(x, 16))
    except: pass

Printing the converted now will give you the list:

[10000, 255]

As you can see, this will work even if hex numbers aren't equally padded with zeroes. You can get the nice and reliablecode playing with similar code formulations.

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