Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode and encode a float in Rust?

I want to decode, store and encode a float in Rust. I know about num::Float::integer_decode() but I'd rather not lose any precision. That is, unless the format I encode into is smaller than the format I encode from of course.

like image 649
Jeroen Avatar asked Dec 18 '22 12:12

Jeroen


2 Answers

Newer versions of Rust provide safer options than some of the other answers suggest:

  • From Rust 1.20, you can use to_bits and from_bits to convert to and from the u64 binary representation.
  • From Rust 1.40, you can use to_be_bytes and from_be_bytes to deal with [u8; 8]. (There are also methods for little-endian byte order and native byte order.)
like image 160
Evan Shaw Avatar answered Jan 16 '23 03:01

Evan Shaw


Interpret the floating point bits as an integer and print out the value as hex:

use std::mem;

fn main() {
    let a_third: f64 = 1.0 / 3.0;

    let as_int: u64 = unsafe { mem::transmute(a_third) };
    println!("{}", as_int);

    let as_string = format!("{:016x}", as_int);
    println!("{}", as_string);

    let back_to_int = u64::from_str_radix(&as_string, 16).expect("Not an integer");
    println!("{}", back_to_int);

    let back_to_float: f64 = unsafe { mem::transmute(back_to_int) };
    println!("{}", back_to_float);

    assert_eq!(back_to_float, a_third);
}
like image 32
Shepmaster Avatar answered Jan 16 '23 01:01

Shepmaster