16

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 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<u8>? Likewise is there a way to convert 4 u8s (in a Vec<u8> say) into an f32?

18

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:

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);
    }
}

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::<i64>()) };

    for i in bs {
        println!("{:X}", i);
    }
}
  • 2
    Using std::slice::from_raw_parts is less code and also marked stable. Still unsafe for the same reasons, though! – bluss Apr 4 '15 at 23:23
  • @user139873, ooh, nice, somehow I missed that such function exists. I've updated the answer. – Vladimir Matveev Apr 4 '15 at 23:44
  • 3
    byteorder solves it exactly. When I said "built in" I should have specified that something from crates.io would suffice. – Rory Apr 7 '15 at 7:53
13

std::mem::transmute can be used, although it is unsafe:

fn main() {
    let var1 = 12345678_i64;
    let raw_bytes: [i8; 8] = unsafe { std::mem::transmute(var1) };
    for byte in &raw_bytes {
        println!("{}", byte);
    }
}

Note: Please be sure the size of the two variables are exactly equal.

-1

If your goal is to print the bytes or have them in a str representation, simply use the :b notation in a format brace

fn main() {
    println!("This is the binary of int {:b}", 4 as i32);
}

This prints

This is the binary of int 100

  • Your answer is absolutely irrelevant to the question asked! – Kamyar Dec 24 '18 at 6:01

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.