Created
July 26, 2022 16:23
-
-
Save mkatychev/6290c0b8602fdeb11d7ab047402178eb to your computer and use it in GitHub Desktop.
As conversion example
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
use std::mem::transmute; | |
fn main() { | |
let num: u32 = u32::MAX; | |
println!("u32: {num}"); | |
println!("u16: {}", num as u16); | |
println!("i32: {}", num as i32); | |
println!("f32: {}", num as f32); | |
let bytes_u32: [u8; 4] = unsafe { transmute(num.to_be()) }; | |
let bytes_u16: [u8; 2] = unsafe { transmute((num as u16).to_be()) }; | |
let bytes_i32: [u8; 4] = unsafe { transmute((num as i32).to_be()) }; | |
let bytes_f32: [u8; 4] = unsafe { transmute((num as f32).to_be_bytes()) }; | |
println!("bytes_u32: {:?}", bytes_u32); | |
println!("bytes_u16: {:?}", bytes_u16); | |
println!("bytes_i32: {:?}", bytes_i32); | |
println!("bytes_f32: {:?}", bytes_f32); | |
println!( | |
"f32::from_be_bytes(bytes_f32): {}", | |
f32::from_be_bytes(bytes_f32) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment