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!
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
.