0

I'm trying to run this code in python 3 it only works in python 2

struct.unpack('f', "".join(map(chr, bytes)))[0]

def get_float(data, index):
    bytes = data[4*index:(index+1)*4]
    return struct.unpack('f', "".join(map(chr, bytes)))[0]

I get this error

Type Error: a byte like object is required, not 'str"

4
  • 1
    What about it doesn't work in Python 3? Commented Apr 16, 2018 at 22:02
  • I get an error saying Type Error: a byte like object is required, not 'str" I'll add the code Commented Apr 16, 2018 at 22:08
  • struct.unpack() takes bytes as a second argument. Commented Apr 16, 2018 at 22:09
  • Sorry im really new to stack exchange give me a second Commented Apr 16, 2018 at 22:12

1 Answer 1

1

You can try the following:

struct.unpack('f', b"".join(map(chr, bytes)))[0]

a b"" is a byte-string. Since the unpack need bytes, you need to use the byte-string join method.

EDIT: you don't need to map your bytes to char. You can use:

struct.unpack('f', bytes)[0]

Note that bytes shadow the class bytes.

Sign up to request clarification or add additional context in comments.

1 Comment

You may want to explain why the b is needed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.