liveBook · Manning

FP32

As explained in Rust in Action: Systems programming concepts and techniques

A single-precision floating-point type is a floating-point type represented with the precision associated with Rust's f32 type.

FP32 is a single-precision floating-point format. Rust’s `f32` uses its 32 bits as three fields: a sign, an exponent, and a fraction. Together they represent a number, rather than an ordinary 32-bit integer. section 5.4.1

Figure 5.1 An overview of the three components encoded within the bits of a floating-point number for the f32 type in Rust

Use the bit-layout diagram to locate the three fields before extracting them in code. section 5.4.1

Take apart 42.42

As an `f32`, `42.42` has the bit pattern `0x4229AE14`. Call `to_bits()` to view it as a `u32`. Shift right by 23 and mask with `0xff` to isolate the eight exponent bits; subtract the bias, 127, to decode the exponent. The fraction bits contribute weighted powers of two to the mantissa. For this value, the decoded sign is positive, the exponent gives a factor of 32, and the mantissa is about 1.325625. section 5.4.1 section 5.4.3

That reconstruction describes ordinary values, not every bit pattern. An exponent field of all zeros permits subnormal values near zero; all ones marks infinities or NaNs. FP32 also has both positive and negative zero. These cases matter when comparing values: the two zeros compare equal, while a NaN does not compare equal to itself. section 5.4.4 section 5.8

Turn a byte into a probability-like value

For a byte `n`, `(n as f32) / 255.0` produces a value from 0 to 1. A bit-manipulation alternative places the byte into an `f32` fraction, constructs the value with `f32::from_bits()`, then scales it. That alternative maps `0xff` to `0.99609375`, not 1: check the endpoints before treating the two methods as interchangeable. section 5.6

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Works through field extraction and reconstruction, while identifying special values that the ordinary-value reconstruction does not handle.
Examples
Dissects `42.42` and converts a `u8` into an `f32` using division or constructed bits.
What it assumes
Assumes basic Rust values and loops, while showing the shifts, masks, and bit weights used to inspect `f32`.
What you can do after
Build it from scratch: extract and decode ordinary `f32` fields, then test a byte-to-`f32` conversion against its endpoints.
How it connects
Connects floating-point representation to bitwise operations, scientific notation, subnormal numbers, NaNs, and equality comparisons.

Also explained in

Compare how 3 books explain FP32 →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.