gpt4 book ai didi

rust - 这是从二进制文件中读取结构的最自然方式吗?

转载 作者:行者123 更新时间:2023-11-29 08:06:23 25 4
gpt4 key购买 nike

我刚刚意识到这与 What is the best way to parse binary protocols with Rust 非常相似


这是使用 Rust 从二进制文件读取结构的最自然方式吗?它可以工作,但看起来有点奇怪(为什么我不能完全填充结构?)。

extern crate byteorder;
use byteorder::{ByteOrder, LittleEndian};

struct Record {
latch: u32,
total_energy: f32,
x_cm: f32,
y_cm: f32,
x_cos: f32,
y_cos: f32,
weight: f32
}

impl Record {
fn make_from_bytes(buffer: &[u8]) -> Record {
Record {
latch: LittleEndian::read_u32(&buffer[0..4]),
total_energy: LittleEndian::read_f32(&buffer[4..8]),
x_cm: LittleEndian::read_f32(&buffer[8..12]),
y_cm: LittleEndian::read_f32(&buffer[12..16]),
x_cos: LittleEndian::read_f32(&buffer[16..20]),
y_cos: LittleEndian::read_f32(&buffer[20..24]),
weight: LittleEndian::read_f32(&buffer[24..28]),
}
}
}

最佳答案

看看 nom crate:解析二进制数据非常有用。

使用 nom,您可以使用类似以下内容(未测试)编写您的解析器:

named!(record<Record>, chain!
( latch: le_u32
~ total_energy: le_f32
~ x_cm: le_f32
~ y_cm: le_f32
~ x_cos: le_f32
~ y_cos: le_f32
~ weight: le_f32
, {
Record {
latch: latch,
total_energy: total_energy,
x_cm: x_cm,
y_cm: y_cm,
x_cos: x_cos,
y_cos: y_cos,
weight: weight,
}
}
)
);

关于rust - 这是从二进制文件中读取结构的最自然方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com