【发布时间】:2013-05-12 01:57:40
【问题描述】:
我正在使用 Python 3.3。
我从串行端口获取数据,得到的每个字节对应一个整数。 (没有数字大于 255,所以没有多字节数字)。
我一直在尝试将其写入人类可读文本的文本文件,所以我寻求帮助。
如果我从我的串口获得值 0b10000111,我如何让这个数字在我的文本文件中显示为“135”?这听起来像一个简单的任务,但我已经很努力了!
我还想添加一个逗号来分隔值(字节)。
这是我一直在尝试的:
import sys
import serial
port = serial.Serial('COM4', 115200)
fileID = open('output.txt', 'a')
while(1):
data = port.read(size=1)
if data != 0:
#MISSING SOME CONVERSION HERE... Tried a lot of things,
#but none have been correct.
fileID.write(data)
fileID.write(',')
【问题讨论】:
-
repr(data)返回什么? -
你尝试了什么,得到了什么?例如,您尝试过
int(data)吗? -
int(data) 和 int(data, 2) 给我错误:“invalid literal for int() with base 2”
-
Blender: print(repr(data)) 例如返回 b'\x98'。
标签: python python-3.x type-conversion