Last active
November 21, 2021 10:59
-
-
Save pidb/6a6e7150de5739a130e82044dbc94b58 to your computer and use it in GitHub Desktop.
Serialize u32 to bytes and Deserialize u32 from bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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