Search code examples
rustfloating-pointhexunsigned-integer

How to specify a floating point number literal using hexadecimal notation In Rust?


I'm implementing xoshiro256++ and I'm able to generate pseudo-random 64-bit unsigned integers. The next challenge is generating uniform doubles in the unit interval from the PRNGs u64's.

a 64-bit unsigned integer x should be converted to a 64-bit double using the expression

(x >> 11) * 0x1.0p-53

How would one evaluate this in Rust? On trying this I get the compile error:

error: hexadecimal float literal is not supported
  --> src/main.rs:30:56
   |
30 |             f64::from_bits((x >> 11).wrapping_mul(0x1.0p-53))
   |                                                        ^^^^^

Solution

  • You can use the hexf crate:

    #[macro_use]
    extern crate hexf;
    
    fn main() {
        let v = hexf64!("0x1.0p-53");
        println!("{}", v);
    }
    

    See also: