Coder
Coder

Reputation: 1899

Convert float64 to hexadecimal in Rust

I would like to know how to convert a float64 (or float32) to a corresponding binary/hexadecimal format. It would be great to be able to specify endianness as well (prefer to print it in little-endian format).

Linked post: How to convert hex string to a float in Rust?

Thanks!

Upvotes: 1

Views: 522

Answers (2)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26559

Use f32::to_be_bytes, f32::to_le_bytes, or f32::to_ne_bytes (depending on the desired endianness) and then format the resulting elements of the array:

let float: f32 = 123.45;
let bytes = float.to_le_bytes();
let hex = format!("{:02X}{:02X}{:02X}{:02X}", bytes[0], bytes[1], bytes[2], bytes[3]);
assert_eq!(hex, "66E6F642");

No need for the unsafe and dangerous transmute.

Rust Playground Link

Upvotes: 3

ShadowRanger
ShadowRanger

Reputation: 155363

It's just the inverse of the operations from the answer to the question you linked:

fn main() {
    // Hex string to 4-bytes, aka. u32
    let float: f32 = 18.9;
    
    let bytes = unsafe { std::mem::transmute::<f32, u32>(float) };
    
    let hex = format!("{:x}", bytes);
    
    // Print 41973333
    println!("{}", hex);
}

Rust Playground link

Call .from_be(), .from_le() or .swap_bytes() on the u32 value (bytes) before formatting to alter the byte order. Change from f32 and u32 to f64 and u64 for larger data types.

Similarly, the other answer to that question (using f32.from_bits) has a direct inverse in f32.to_bits (though those functions are still marked as unstable).

Upvotes: 0

Related Questions