使用Python套接字连接时,我从服务器(模拟器)收到以下内容:
'C\xbc\x7fZC\xbc\x7f5C\xbc\x7f&C\xbc\x7f!C\xbc\x7f\x14C\xbc\x7f\x16C\xbc\x7f!C\xbc\x7f\x12C\xbc\x7f\x19C\xbc\x80\x03C\xbc\x81~C\xbc\x80FC\xbc\x7f\xd1C\xbc~\xcdC\xbc~\xd7C\xbc\x7f$;4\xe0\xb8;\x81\xf6\xd7;R\xf4T:\xc5v\xb4:\xc1>\xc1:\xd9\x15\x9a:\xa8M7;K\xde{:\xfb\\\xcd\xbc\tR\xd4\xba\xe1\xb6\xf3\xbb\xc9\xb8\xf4\xbby\x8a\x199\x9dH\x009\x0cp\x00:\xeb<\x00'
但我的实际输出应该是(大小为32x1):
376.99493 376.99380 376.99335 376.99319 376.99280 376.99286
376.99319 376.99274 376.99295 377.00009 377.01166 377.00214
376.99857 376.99063 376.99094 376.99329 0.0027599763
0.0039661932 0.0032189088 0.0015065284 0.0014743434
0.0016562224 0.0012840395 0.0031107950 0.0019177437
-0.0083815642 -0.0017220661 -0.0061560813 -0.0038076697
0.00029999018 0.00013393164 0.0017946959
如何转换ASCII代码以在Python 2.7中获取这些数字。
答案 0 :(得分:1)
要从套接字转换浮点数,您可以使用struct.unpack
。
num_floats = int(len(raw_data) / 4)
format_str = '>' + 'f' * num_floats
data = struct.unpack(format_str, raw_data[:num_floats * 4])
import struct
raw_data = b'C\xbc\x7fZC\xbc\x7f5C\xbc\x7f&C\xbc\x7f!C\xbc\x7f\x14C\xbc' \
b'\x7f\x16C\xbc\x7f!C\xbc\x7f\x12C\xbc\x7f\x19C\xbc\x80\x03C' \
b'\xbc\x81~C\xbc\x80FC\xbc\x7f\xd1C\xbc~\xcdC\xbc~\xd7C\xbc' \
b'\x7f$;4\xe0\xb8;\x81\xf6\xd7;R\xf4T:\xc5v\xb4:\xc1>\xc1:\xd9' \
b'\x15\x9a:\xa8M7;K\xde{:\xfb\\xcd\xbc\tR\xd4\xba\xe1\xb6\xf3' \
b'\xbb\xc9\xb8\xf4\xbby\x8a\x199\x9dH\x009\x0cp\x00:\xeb'
num_floats = int(len(raw_data) / 4)
format_str = '>' + 'f' * num_floats
data = struct.unpack(format_str, raw_data[:num_floats * 4])
print(data)
(376.99493408203125, 376.9938049316406, 376.99334716796875,
376.9931945800781, 376.9927978515625, 376.99285888671875,
376.9931945800781, 376.99273681640625, 376.9929504394531,
377.0000915527344, 377.01165771484375, 377.00213623046875,
376.9985656738281, 376.9906311035156, 376.9909362792969,
376.9932861328125, 0.00275997631251812, 0.003966193180531263,
0.0032189087942242622, 0.001506528351455927, 0.0014743433566763997,
0.001656222390010953, 0.001284039462916553, 0.003110795048996806,
0.0019177338108420372, 4.2194070097596986e+21, 456834187264.0,
-7.263825409609126e-06, -0.00011669746163534, -7.377517891143851e-33,
131300.1875, 1.5874123484317317e+29)