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 u32::to_ne_bytes
, and then reads the numbers back with u32::from_ne_bytes
. The u64
methods are also used.
u8
values (bytes) and then use extend_from_slice
to append multiple bytes from the to_ne_bytes
method results.read_to_end
to do this.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
.