Converting number primitives (i32, f64, etc) to byte representations

Rust 1.40 has: {to,from}_{ne,le,be}_bytes.

Converting a number to bytes and back (works for floats and integers after rust 1.40):

let x = 65535_i32;
let x_bytes = x.to_be_bytes();                  // x_bytes = [0, 0, 255, 255]
let original_x = i32::from_be_bytes(x_bytes);   // original_x = 65535 = x

Converting float before Rust 1.40

Rust 1.32 has: {to,from}_{ne,le,be}_bytes (only for integers), to_bits, and from_bits.

Converting a float to bytes and back:

let y = 255.255_f32;
let y_bytes = y.to_bits().to_be_bytes();
let original_y = f32::from_bits(u32::from_be_bytes(y_bytes)); // original_y = 255.255 = y

According to the Rust documentation from_bits can have portability issues.


As of Rust 1.32 you can use {to,from}_{ne,le,be}_bytes for integral types.

let begin = 1234_i32;
let bytes = begin.to_ne_bytes();
let and_back = i32::from_ne_bytes(bytes);

For floating point you still have to rely on prior methods.

Tags:

Types

Rust