我有一个以字节数组表示的数据。需要将数据解压缩到python数组:
在C#中,它的外观(start=4):
static T BytesToStructure<T>(byte[] bytes, int start)
{
int size = Marshal.SizeOf(typeof(T));
if (bytes.Length < size)
throw new Exception("Invalid parameter");
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, start, ptr, size);
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}我也试过在蟒蛇身上做同样的事情。但是它不能正常工作。
import struct
decode_buf = [251,0,160,64,217,53,223,189,98,22,36,191,214,90,91,63,0,144,238,178,0,176,31,180,0,16,70,51,106,43,30,187,96,88,149,58,74,186,9,58,16,204,136,60,0,167,2,189,187,214,28,65,221,101,123,63,98,208,59,62,216,163,181,188,230,152,30,189,76,19,180,20]
parsed_data = struct.unpack_from("<H", bytes(decode_buf))正确的输出必须是:
data{
acc: [0] = 0.01669887
acc: [1] = -0.03189754
acc: [2] = 9.802424
gyo: [0] = -0.002413476
gyo: [1] = 0.001139414
gyo: [2] = 0.0005253894
pos_glob_odometry: [0] = -0.1089894
pos_glob_odometry: [1] = -0.6409665
pos_glob_odometry: [2] = 0.8568548
rot: [0] = 0.9820231
rot: [1] = 0.1834121
rot: [2] = -0.02217285
rot: [3] = -0.03872003
vel: [0] = -2.777233E-08
vel: [1] = -1.487206E-07
vel: [2] = 4.611502E-08
} 发布于 2022-11-15 09:37:25
您忽略了struct中的某些内容,您必须指定字节数组中的十六进制数:
parsed_data = struct.unpack_from("<%de" % int(len(bytes(decode_buf)) / 2),bytes(decode_buf))Note1:除以2,因为'e‘意味着在两个字节上浮动值,所以您应该有len//2 16位项。
Note2:确保decode_buf是mod 2(最终添加填充)
https://stackoverflow.com/questions/74443106
复制相似问题