如何在ASCII二进制字段中打印

时间:2016-03-04 16:53:20

标签: string python-2.7

我熟悉C ++,我尝试开始使用python。

从串行线我设法用python接收一串二进制字符(不是ASCII),比方说rx'缓冲区'。 我必须将此字符串拆分为不同的字段,我使用的方法是:

stx = (rx[0]) 
ctl = (rx[1])
node = (rx[2])
cTime = (rx[3:6])
nTime = (rx[7:10])
etx = (rx[11])

(目前我还没有找到一种方法来定义C ++的结构)。

现在我的问题是通常使用以下方式将这些字段打印为ASCII:

print "%d-%d-%d-%ld-%ld-%d" % (stx,ctl,node,cTime,nTime,etx)

错误消息是:

TypeError: %d format: a number is required, not str

我已经尝试过转换不同格式的字段,但没有任何作用。 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

You probably need to convert your variables to numbers by float(stx) (or int) but if you only want to print them just use %s instead of %d which expects the variable to be a double (meaning float).

For example:

rx = '1' * 12
stx = float(rx[0]) 
ctl = float(rx[1])
node = float(rx[2])
cTime = float(rx[3:6])
nTime = float(rx[7:10])
etx = float(rx[11])

print "%d-%d-%d-%ld-%ld-%d" % (stx,ctl,node,cTime,nTime,etx)

prints

1-1-1-111-111-1

or with strings you change the last line:

print "%s-%s-%s-%s-%s-%s" % (stx,ctl,node,cTime,nTime,etx)

In case you are dealing with raw binary data you might need the builtin struct module.

As far as I understand it (given you haven't posted an actual content and desired output I cannot verify it) you might want something like:

import struct
stx, ctl, node, cTime, nTime, etx = struct.unpack('fffddf', rx)

That would expect 3 floats, 2 doubles and then again 1 float. If you have integer or other datatypes you must edit the fffddf string. See the format types of struct

答案 1 :(得分:0)

Brrr awfull

我终于找到了这种简单功能的一种方法:

> print int(stx.encode('hex'),16),int(ctl.encode('hex'),16),
> int(node.encode('hex'), 16), int(cTime.encode('hex'), 16),
> int(nTime.encode('hex'), 16),  int(etx.encode('hex'), 16)

不确定我会不会喜欢python