Skip to content
Tech News
← Back to articles

Printing floating point numbers in binary

read original more articles
Why This Matters

This article highlights a novel approach to converting floating point numbers into binary by leveraging their hexadecimal representations in Python. Understanding this process is crucial for developers working with low-level data manipulation, debugging, or optimizing numerical computations, as it enhances transparency and control over floating point representations in digital systems.

Key Takeaways

It’s well known that you can convert the base 16 (hex) representation of an integer to the base 2 (binary) representation by simply converting each digit from hex to binary. For example,

CAFE hex = 1100 1010 1111 1110 two

I imagine it’s less well known that you can do the same thing with floating point numbers.

I wanted to find the binary representation of a floating point number using Python, and discovered that it has no function to do this. However, there is a method on floats to show a hex representation. For example, here’s the hex representation of π.

>>> import math >>> (math.pi).hex() '0x1.921fb54442d18p+1'

Curiously, the p+k part at the end is an exponent of 2, not an exponent of 16. So after we convert 1.921fb54442d18 to binary, we’ll need to multiply by 2, i.e. move the fractional point one space to the right.

So first we convert 1.921fb54442d18 hex to binary by converting 1, 9, 2, etc. each to binary.

1.1001 0010 0001 1111 1011 0101 0100 0100 0100 0010 1101 0001 1000 two

Then after shifting the fraction point to account for the p+1 part we have

π = 11.001001000011111101101010100010001000010110100011000 two

... continue reading