U32, to_ne_bytes. How can we convert values such as u32 into bytes and back again? And how can we write these bytes to a file, and then get them back as u32 values?
With built-in methods from the Rust standard library, we can perform these conversions. We the native encoding, we can just use whatever numeric encoding the current computer uses.
This example writes a file containing 3 values. The numbers are encoded to bytes with the to_ne_bytes methods. It then reads the numbers back with from_ne_bytes.
Part 1 We create a vector of u8 values (bytes) and then use extend_from_slice to append multiple bytes from the to_ne_bytes method results.
Part 4 With the u32 and u64 from_ne_bytes, we turn the groups of values in arrays (created with the try_into cast) back into the original types.
use std::fs::File;
use std::io::*;
fn main() {
// Part 1: fill a vector with some bytes based on 3 values.
let path = "file.txt";
let mut write_buffer = vec![];
write_buffer.push(10_u8);
write_buffer.extend_from_slice(&u32::to_ne_bytes(10000));
write_buffer.extend_from_slice(&u64::to_ne_bytes(1000000));
// Part 2: write the buffer to the disk.
let mut f = File::create(path).unwrap();
f.write_all(&write_buffer).ok();
// Part 3: read the file from the disk.
let mut read_buffer = vec![];
let mut f = File::open(path).unwrap();
f.read_to_end(&mut read_buffer).ok();
// Part 4: read back in the 3 original values from the file's data.
let mut i = 0;
let v = read_buffer[i];
i += 1;
let v2 = u32::from_ne_bytes(read_buffer[i..i + 4].try_into().unwrap());
i += 4;
let v3 = u64::from_ne_bytes(read_buffer[i..i + 8].try_into().unwrap());
i += 8;
println!("{} {} {}", v, v2, v3);
}10 10000 1000000
Rust programs often read and write files containing numeric values. And when these values are more than 1 byte, we often need to use from_ne_bytes and to_ne_bytes.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.