Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the byte class object into a string object

import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *

data = serial.Serial('com3',115200)
while True:
    while (data.inWaiting() == 0):
    pass
ardstr = data.readline()
print (ardstr)

Here I am trying to get data from arduino but it is coming in the format b'29.20\r\n'. I want to have the data in the format "29.20" so I can plot it.

I tried ardstr = str(ardstr).strip('\r\n') and ardstr.decode('UTF-8') but none of them is working. My python version is 3.4.3.

What can I do to get the result as "29.40" rather than "b'29.20\r\n'"?

like image 844
Sajal Avatar asked Jun 29 '18 15:06

Sajal


People also ask

How can we convert objective byte to string?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Is byte [] same as string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

How do you convert bytes to long objects?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();


1 Answers

I tried ardstr = str(ardstr).strip('\r\n') and ardstr.decode('UTF-8')

You were close! As with the .strip() call, using the .decode() method returns the new value.

ardstr = ardstr.strip()
ardstr = ardstr.decode('UTF-8')
like image 104
wim Avatar answered Oct 06 '22 05:10

wim