0

The standard write_all and write functions from the std::fs crate allow to write string slices (so technically &[u8]?) to files.

Is there a way to write hex-numbers directly to the file?

sshashank124
  • 31,495
  • 9
  • 67
  • 76
MEisebitt
  • 122
  • 7
  • How are you representing the hex numbers? As strings? – SCappella Jan 12 '20 at 00:22
  • @SCappella as number literal e.g. 0xff – MEisebitt Jan 12 '20 at 01:04
  • That means that this reduces to writing slices of numeric types other than `u8` to files (unless all your hex numbers are less than 256, in which case you can just put them in a `&[u8]` and write that). For that, see [this question](https://stackoverflow.com/questions/30838358/what-is-the-correct-way-to-write-vecu16-content-to-a-file). Two implementations: [here](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7af590520838b055887f668fad9e9982) or [here](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6cfc4398b13b74d84d533b44045b8676). – SCappella Jan 12 '20 at 01:39
  • Why don't you post an input example as well as your desired output. To me, it seems like you want to do the following: `format!("0x{:0>2X}", 15) -> "0x0F"` – richardpringle Jan 13 '20 at 20:03

1 Answers1

2

You can use this function:

use std::io::{Result, BufWriter, Write};

fn write_hex<W: Write>(file: &mut BufWriter<W>, data: &[u8]) -> Result<()> {
    for val in data {
        write!(file, "{:02X}", val)?;
    }
    Ok(())
}

playground

Since it writes each hex number individually, it requires that you use a buffered stream. You can create one with BufWriter::new(file). You can change {:02X} to {:02x} to write lower case hex instead.

Alice Ryhl
  • 3,574
  • 1
  • 18
  • 37
  • A little functional touch if needed : [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=843f489db6a90b9f7052e36ab62b23b3), also doc advises to flush `BufWriter` before it is dropped. – Ömer Erden Jan 27 '20 at 09:51