简体   繁体   English

将字节转换为Int时出错(Python 2.7)

[英]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. 我正在Python 2.7中工作,并且正在读取字节数据(这是一个.ecg文件),但是我需要将其转换为整数值。

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'

It looks like you're reading binary data, not ASCII numbers, so you need a different way to convert: the struct module . 看起来您正在读取二进制数据,而不是ASCII数字,因此您需要一种不同的转换方式: 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))

int() converts a string representation of digits such as '1' to an integer. int()数字的字符串表示形式(例如'1' int()转换为整数。 If you want to convert a one-character bytestring to an integer, you can use ord() . 如果要将一个字符的字符串转换为整数,可以使用ord() However, if you want to convert more than one byte at a time you can use the struct module, specifically struct.unpack . 但是,如果您想一次转换多个字节,则可以使用struct模块,特别是struct.unpack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM