mahjongg
mahjongg

Reputation: 19

how to convert a byte array with an ascii decimal number to integer in Python 3

I am trying to communicate serially with an arduino which is sending me the results of polling an ADC channel, in the form of an ASCII string with the decimal result, which is normally appended with an EOT character ('\x04'). so typical results I might expect from PySerial are:

b'0\x04'

for the integer 0, or

b'293\x04'

for the integer 293, or even

b'1023\x04'

for the highest possible value, 1023.

On the PC side i'm running python 3.2 (on Windows 7).

I want to convert the received bytes from PySerial into an integer, so I can calculate with them.

How do I convert the byte array into an integer?

I am able to stop the arduino from sending the EOT character after the numerical value, but it is probably safer to leave them in.

I'm a beginner with Python, but not so much with C.

Upvotes: 1

Views: 1381

Answers (1)

vaultah
vaultah

Reputation: 46533

Strip the EOT character from the right side and feed the result to int

>>> int(b'1023\x04'.rstrip(b'\x04'))
1023

Upvotes: 3

Related Questions