Skip to main content

Crate fhex

Crate fhex 

Source
Expand description

Hex float conversion for f32 and f64.

This crate provides two traits:

  • ToHex for formatting floats as hex strings (0x1.8p+1)
  • FromHex for parsing hex strings back to floats

The format follows the IEEE 754 hex float specification—the same format used by C’s %a printf specifier, Java’s Double.toHexString(), and the WebAssembly text format.

§Examples

use fhex::{ToHex, FromHex};

// Formatting
let hex = 3.0_f64.to_hex();
assert_eq!(hex, "0x1.8p+1");

// Parsing
let value = f64::from_hex("0x1.8p+1").unwrap();
assert_eq!(value, 3.0);

// Round-trip
let original = std::f64::consts::PI;
let roundtrip = f64::from_hex(&original.to_hex()).unwrap();
assert_eq!(original, roundtrip);

§Format

Floating point numbers are represented as ±0xh.hhhp±d, where:

  • ± is the sign (- for negative, omitted for positive)
  • 0x is the hex prefix
  • h.hhh is the significand in hexadecimal
  • p±d is the exponent in decimal (base 2)

Special values:

  • ±0x0p+0 for zero
  • ±inf for infinity
  • nan for quiet NaN
  • nan:0x... for NaN with payload (signalling NaN)

§Panics

Neither ToHex::to_hex nor FromHex::from_hex will panic. All inputs are handled gracefully.

Traits§

FromHex
Trait for parsing hexadecimal strings to floating-point numbers.
ToHex
Trait for converting floating-point numbers to hexadecimal strings.