Skip to content

Instantly share code, notes, and snippets.

@pidb
Last active November 21, 2021 10:59
Show Gist options
  • Save pidb/6a6e7150de5739a130e82044dbc94b58 to your computer and use it in GitHub Desktop.
Save pidb/6a6e7150de5739a130e82044dbc94b58 to your computer and use it in GitHub Desktop.
Serialize u32 to bytes and Deserialize u32 from bytes
/// idea from https://docs.rs/byteorder/1.4.3/src/byteorder/lib.rs.html
#![allow(unused)]
fn main() {
let mut x: Vec<u8> = Vec::new();
x.reserve(16);
let y: u32 = 12;
unsafe {
// write y to byte array
std::ptr::copy_nonoverlapping(
y.to_ne_bytes().as_ptr(),
x.as_mut_ptr().offset(8),
std::mem::size_of::<u32>(),
);
// read y from byte array
let mut y_bytes: [u8; 4] = [0; 4];
std::ptr::copy_nonoverlapping(
x.as_ptr().offset(8),
y_bytes.as_mut_ptr(),
std::mem::size_of::<u32>(),
);
println!("{}", std::mem::transmute::<[u8; 4], u32>(y_bytes));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment