This is an example of how to use the library.
This example converts a 32-bit floating point value to and from a byte array.
This commit is contained in:
parent
039c093b92
commit
8ae59008fe
72
examples/convert_f32.rs
Normal file
72
examples/convert_f32.rs
Normal file
@ -0,0 +1,72 @@
|
||||
#![feature(convert)]
|
||||
|
||||
extern crate alchemy;
|
||||
|
||||
|
||||
use std::f32;
|
||||
|
||||
use alchemy::{PlatformEndian, Transmutable};
|
||||
|
||||
|
||||
|
||||
pub fn main()
|
||||
{
|
||||
let num: f32;
|
||||
let mut final_num: f32;
|
||||
let mut buffer: [u8; 4];
|
||||
|
||||
// Initialize the variables.
|
||||
num = 6.291985f32;
|
||||
final_num = f32::NAN;
|
||||
buffer = [0u8; 4];
|
||||
|
||||
println!("Converting the value {} into and out of an array of bytes.", num);
|
||||
println!("Buffer starts as: {}", stringify_array(&buffer));
|
||||
|
||||
// Convert the floating point number into an array of bytes.
|
||||
PlatformEndian::f32_to_bytes(&mut buffer, num);
|
||||
|
||||
println!("Buffer contains: {}", stringify_array(&buffer));
|
||||
|
||||
// Convert the array of bytes into a floating point number.
|
||||
final_num = PlatformEndian::bytes_to_f32(&buffer);
|
||||
println!("The buffer converts back to: {}", final_num);
|
||||
}
|
||||
|
||||
/// This just help pretty up the printing of an array of bytes.
|
||||
fn stringify_array(buffer: &[u8]) -> String
|
||||
{
|
||||
let mut result: String;
|
||||
let mut count: usize;
|
||||
|
||||
// Create a new string that starts with just
|
||||
// the array opening bracket.
|
||||
result = String::new();
|
||||
result.push_str("[");
|
||||
|
||||
// Loop through the buffer keeping track
|
||||
// of our place in it.
|
||||
count = 0usize;
|
||||
for byte in buffer
|
||||
{
|
||||
// Handle priting the last value differently.
|
||||
if count >= buffer.len() - 1
|
||||
{
|
||||
result.push_str(byte.to_string().as_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
result.push_str(byte.to_string().as_str());
|
||||
result.push_str(", ");
|
||||
}
|
||||
|
||||
// Mark that we are going to look at
|
||||
// the next byte in the array.
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// Add the array closing bracket and
|
||||
// return the new String.
|
||||
result.push_str("]");
|
||||
result
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user