Fixed-point Q format converter

Converts a real number to a fixed-point word with W bits, F of them fractional, and back. The parameters match MATLAB fixdt(signed, W, F): Q0.15 is a signed 16-bit word with 15 fractional bits.

Format
Real value to fixed point
Bit pattern to real value

Q notation
-
Resolution
-
Range
-
Stored integer
-
Hex
-
Binary
-
Quantized value
-
Quantization error
-
Pattern as a real value
-

How it works

stored integer = round(x · 2F), xq = stored integer · 2−F

A signed word covers −2W−1 to 2W−1 − 1 stored values, an unsigned one 0 to 2W − 1; the real range is that times the resolution 2−F. Saturation clamps values outside the range to its ends; wrapping keeps the low W bits, as most RTL does when nothing else is coded.

Q notation differs between vendors. Here Qm.n counts m integer bits without the sign bit, so a signed word has W = m + n + 1 bits; UQm.n is unsigned with W = m + n.

Need this in RTL, in a MATLAB model or on real hardware? Discuss your project.