patternrustModerate
Converting number primitives (i32, f64, etc) to byte representations
Viewed 0 times
f64convertingbyterepresentationsnumberprimitivesi32etc
Problem
I am writing a library that encodes/decodes data to/from a binary format. Part of the format is numbers, which I'm using Rust's native primitive types for (like
Is there an easy, built-in way to convert these data types into/from binary, i.e. convert a
i8, i64, f32 etc.).Is there an easy, built-in way to convert these data types into/from binary, i.e. convert a
f64/f32/i64/etc. into a Vec? Likewise is there a way to convert 4 u8s (in a Vec say) into an f32?Solution
Unfortunately, there is no safe built-in support for reading/writing primitives from/to a byte array in Rust at the moment. There are several community libraries for that, however, byteorder being the most used one:
Of course, you can always cast raw pointers. For example, you can turn
extern crate byteorder;
use byteorder::{LittleEndian, WriteBytesExt};
use std::mem;
fn main() {
let i: i64 = 12345;
let mut bs = [0u8; mem::size_of::()];
bs.as_mut()
.write_i64::(i)
.expect("Unable to write");
for i in &bs {
println!("{:X}", i);
}
}Of course, you can always cast raw pointers. For example, you can turn
const i64 into const i8 and then convert it into an appropriate byte slice &[u8]. However, this is easy to get wrong, unsafe and platform-dependent due to endiannness, so it should be used only as a last resort:use std::{mem, slice};
fn main() {
let i: i64 = 12345;
let ip: *const i64 = &i;
let bp: *const u8 = ip as *const _;
let bs: &[u8] = unsafe { slice::from_raw_parts(bp, mem::size_of::()) };
for i in bs {
println!("{:X}", i);
}
}Code Snippets
extern crate byteorder;
use byteorder::{LittleEndian, WriteBytesExt};
use std::mem;
fn main() {
let i: i64 = 12345;
let mut bs = [0u8; mem::size_of::<i64>()];
bs.as_mut()
.write_i64::<LittleEndian>(i)
.expect("Unable to write");
for i in &bs {
println!("{:X}", i);
}
}use std::{mem, slice};
fn main() {
let i: i64 = 12345;
let ip: *const i64 = &i;
let bp: *const u8 = ip as *const _;
let bs: &[u8] = unsafe { slice::from_raw_parts(bp, mem::size_of::<i64>()) };
for i in bs {
println!("{:X}", i);
}
}Context
Stack Overflow Q#29445026, score: 39
Revisions (0)
No revisions yet.