Blacktiger800
Blacktiger800

Reputation: 55

How to convert b'\xc8\x00' to float?

I actually get a value (b'\xc8\x00') from a temperature sensor. I want to convert it to a float value. Is it right, that I need to decode it?

Here is my function:

def ToFloat(data):
    s = data.decode('utf-8')
    print(s)
    return s

But when I try to compile it, I get the error:

'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte

Upvotes: 0

Views: 1475

Answers (2)

user7711283
user7711283

Reputation:

Notice that ToFloat() is a bit irritating as it returns a float but interpretes the data as integer values. If the bytes are representing a float, it would be necessary to know in which format the float is packed into these two bytes (usually float takes more than two bytes).

data = b'\xc8\x00'
def ToFloat(data):
    byte0 = int(data[0])
    print(byte0)
    byte1 = int(data[1])
    print(byte1)
    number = byte0 + 256*byte1
    print(number)
    return float(number)    

returns: 200.0 what seems to be reasonable. If not, just see what the data mean and process accordingly.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78554

You seem to be having packed bytes not unicode objects. Use struct.unpack:

In [3]: import struct
In [4]: struct.unpack('h', b'\xc8\x00')[0]
Out[4]: 200

Format h specifies a short value (2 bytes). If your temperature values will always be positive, you can use H for unsigned short:

import struct

def to_float(data):
    return float(struct.unpack('H', data)[0])

Upvotes: 2

Related Questions