【问题标题】:Read large f64 binary file into array将大型 f64 二进制文件读入数组
【发布时间】:2021-09-15 02:25:23
【问题描述】:

我正在寻找有关如何将相对较大 (>12M) 的双精度数字二进制文件读入 rust 数组的帮助/示例。我有关于文件中 f64 值数量的元数据。

我已经阅读并看到了byteorder crate,但没有发现文档/示例特别有用。

这不是需要 BufRead 的东西,因为这可能不会提高性能。

谢谢!

【问题讨论】:

  • 您是否遇到了特别的困难?将 8 个字节读入缓冲区并使用 bincode 将其转换为 f64 似乎非常困难。
  • 最简单的方法是使用byteorder crate 中的read_f64_into

标签: rust io binaryfiles binary-data


【解决方案1】:

最简单的方法是读取 8 个字节并使用 f64::from_byte-order_bytes() 方法之一将其转换为 f64

这些方法是这样使用的:

let mut buffer = [0u8; 8]; // the buffer can be reused!
reader.read_exact(&mut buffer) ?;
let float = f64::from_be_bytes(buffer);

因此,您可以一次读取 8 个字节的文件,也可以读取一些更大的块:

fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("./path/to/file")?;
    let mut reader = BufReader::new(file);

    let mut buffer = [0u8; 8];
    loop {
        if let Err(e) = reader.read_exact(&mut buffer) {
            // if you know how many bytes are expected, then it's better not to rely on `UnexpectedEof`!
            if e.kind() == ErrorKind::UnexpectedEof {
                // nothing more to read
                break;
            }

            return Err(e.into());
        }

        // or use `from_le_bytes()` depending on the byte-order
        let float = f64::from_be_bytes(buffer);
        //do something with the f64
        println!("{}", float);

    }

    Ok(())
}

如果您不介意为您的项目添加额外的依赖项,那么您也可以使用具有convenience methodsByteOrder crate 来读取整个切片:

use byteorder::{ByteOrder, LittleEndian};

let mut bytes = [0; 32]; // the buffer you've read the file into
let mut numbers_got = [0.0; 4];

LittleEndian::read_f64_into(&bytes, &mut numbers_got);
assert_eq!(numbers_given, numbers_got)

【讨论】:

  • 感谢@svetlin,我的困惑源于读者而不是数据格式
猜你喜欢
  • 2011-05-14
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
相关资源
最近更新 更多