Skip to content

Commit 9fa3bf3

Browse files
tgross35quaternic
andcommitted
Introduce hf32! and hf64! macros for hex float support
Rust does not have any native way to parse hex floats, but they are heavily used in the C algorithms that we derive from. Introduce a const function that can parse these, as well as macros `hf32!` and `hf64!` that ensure the string literals get handled at compiler time. These are currently not used but making everything available now will ease future development. Co-authored-by: quaternic <[email protected]>
1 parent d833428 commit 9fa3bf3

File tree

4 files changed

+430
-26
lines changed

4 files changed

+430
-26
lines changed

CONTRIBUTING.md

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -44,37 +44,19 @@ Check [PR #65] for an example.
4444
`mod.rs`.
4545

4646
- You may encounter weird literals like `0x1p127f` in the MUSL code. These are hexadecimal floating
47-
point literals. Rust (the language) doesn't support these kind of literals. The best way I have
48-
found to deal with these literals is to turn them into their integer representation using the
49-
[`hexf!`] macro and then turn them back into floats. See below:
47+
point literals. Rust (the language) doesn't support these kind of literals. This crate provides
48+
two macros, `hf32!` and `hf64!`, which convert string literals to floats at compile time.
5049

51-
[`hexf!`]: https://crates.io/crates/hexf
52-
53-
``` rust
54-
// Step 1: write a program to convert the float into its integer representation
55-
#[macro_use]
56-
extern crate hexf;
57-
58-
fn main() {
59-
println!("{:#x}", hexf32!("0x1.0p127").to_bits());
60-
}
61-
```
62-
63-
``` console
64-
$ # Step 2: run the program
65-
$ cargo run
66-
0x7f000000
67-
```
68-
69-
``` rust
70-
// Step 3: copy paste the output into libm
71-
let x1p127 = f32::from_bits(0x7f000000); // 0x1p127f === 2 ^ 12
72-
```
50+
```rust
51+
assert_eq!(hf32!("0x1.ffep+8").to_bits(), 0x43fff000);
52+
assert_eq!(hf64!("0x1.ffep+8").to_bits(), 0x407ffe0000000000);
53+
```
7354

7455
- Rust code panics on arithmetic overflows when not optimized. You may need to use the [`Wrapping`]
75-
newtype to avoid this problem.
56+
newtype to avoid this problem, or individual methods like [`wrapping_add`].
7657

7758
[`Wrapping`]: https://doc.rust-lang.org/std/num/struct.Wrapping.html
59+
[`wrapping_add`]: https://doc.rust-lang.org/std/primitive.u32.html#method.wrapping_add
7860

7961
## Testing
8062

0 commit comments

Comments
 (0)