将套接字接收的字节转换为Python 3中的float

时间:2018-11-20 04:14:48

标签: python struct byte ascii

我尝试按照此处建议的答案进行操作,但未获得预期的结果: Python Socket Received ASCII convert to actual numbers (float)

我正在使用socket.recv()接收字节格式的数据:

      b'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'

我正在尝试以30个浮点数的形式接收上面的值。

我了解我们必须使用struct库,但是在尝试掌握格式概念时遇到了困难。

1 个答案:

答案 0 :(得分:0)

您输入的浮点数不是固定长度的,除了有6个小数步长(如果有的话)之外。那么,为什么不只使用bytes.decode(),然后去掉括号,然后以逗号分隔呢?

每个步骤均已分解:

>>> b = b'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'
>>> b.decode()
'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'
>>> b.decode()[1:-1]
'1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'
>>> b.decode()[1:-1].split(',')
['1', '3', '-121.551552', '-123.602531', '-40.582172', '0', '0', '0', '0', '0', '0', '0',
 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
>>> [float(x) for x in b.decode()[1:-1].split(',')]
[1.0, 3.0, -121.551552, -123.602531, -40.582172, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
 0.0, 0.0, 0.0, 0.0]

另一种 Pythonic 方法可以完成最后一步:

>>> list(map(float, b.decode()[1:-1].split(',')))
[1.0, 3.0, -121.551552, -123.602531, -40.582172, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]