jrs11
jrs11

Reputation: 49

Error Converting Bytes to Int (Python 2.7)

I am working in Python 2.7 and am reading in data as bytes (it's a .ecg file), but I need to convert it to integer values.

packetID = int(holter.read(1), 2)
packetSS = int(holter.read(2), 2)
packetFB = int(holter.read(2), 2)

This returns the error

invalid literal for int() with base 2: '\x01'

Upvotes: 1

Views: 827

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308196

It looks like you're reading binary data, not ASCII numbers, so you need a different way to convert: the struct module.

import struct
packetID = struct.unpack('B', holter.read(1))[0]
packetSS = struct.unpack('H', holter.read(2))[0]

Alternatively you can read them all at once:

packetID, packetSS, packetFB = struct.unpack('BHH', holter.read(5))

Upvotes: 2

Jason S
Jason S

Reputation: 13779

int() converts a string representation of digits such as '1' to an integer. If you want to convert a one-character bytestring to an integer, you can use ord(). However, if you want to convert more than one byte at a time you can use the struct module, specifically struct.unpack.

Upvotes: 0

Related Questions