Back to topic
Optional
Decode FP32 bit fields
Split 32 bits into sign/exponent/mantissa; rebuild ±1.f×2^e and match numpy.float32.
- Version
- v2
- Minutes
- ~20
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
CA · Разбор битов FP32 / Decode FP32 bit fields
Activity version: 2 · Seed: n/a · Данные: IEEE 754 single patterns from the floating-point topic (0xC1480000, 0x3DCCCCCD).
Split 32 bits into sign / exponent / fraction; rebuild and match numpy.float32.
Ожидаемые числа
| Pattern | significand | value | |||
|---|---|---|---|---|---|
0xC1480000 |
|||||
0x3DCCCCCD |
≈ | ≈ (not exact) |
Самопроверка в ноутбуке
Активность не входит в процент освоения.
import numpy as np
def decode_fp32(bits: int):
bits = int(bits) & 0xFFFFFFFF
s = (bits >> 31) & 1
E = (bits >> 23) & 0xFF
frac = bits & 0x7FFFFF
assert 0 < E < 255, "normalized numbers only"
e = E - 127
sig = 1.0 + frac / float(1 << 23)
value = ((-1.0) ** s) * sig * (2.0 ** e)
return s, E, e, frac, sig, value
s, E, e, frac, sig, value = decode_fp32(0xC1480000)
print("0xC1480000", s, E, e, sig, value)
assert (s, E, e) == (1, 130, 3)
assert frac == 0x480000
assert sig == 1.5625
assert value == -12.5
assert int(np.float32(-12.5).view(np.uint32)) == 0xC1480000
s2, E2, e2, frac2, sig2, value2 = decode_fp32(0x3DCCCCCD)
print("0x3DCCCCCD", s2, E2, e2, sig2, value2)
assert (s2, E2, e2) == (0, 123, -4)
assert abs(value2 - 0.1) < 1e-7
assert value2 != 0.1
assert int(np.float32(0.1).view(np.uint32)) == 0x3DCCCCCD
print("OK: FP32 bit decode")
Самопроверка в ноутбуке
-
0xC1480000→ (sign 1, , , sig ) -
0x3DCCCCCD≈ , но!= 0.1точно - round-trip с
numpy.float32совпал