以二进制格式打印浮点数
Printing floating point numbers in binary

原始链接: https://www.johndcook.com/blog/2026/07/27/float-binary/

虽然十六进制数字可以通过展开每一位轻松转换为二进制,但这一过程同样适用于浮点数。Python 虽然缺乏直接显示浮点数二进制表示的函数,但其 `float.hex()` 方法提供了一个有用的中间途径。 浮点数的十六进制表示(例如 `0x1.921fb54442d18p+1`)包含一个表示以 2 为底的指数的 `p+k` 后缀。将其转换为二进制的方法如下: 1. 将每个十六进制数字转换为其对应的四位二进制数。 2. 根据以 2 为底的指数调整二进制小数点的位置。 在处理小数部分时,只要注意必要的补位(例如确保十六进制数字“7”表示为 `0111` 而非 `111`),就可以使用 Python 的 `bin()` 函数处理十六进制数字。通过系统地转换和移位,即可推导出任何浮点数的精确二进制表示。

Hacker News 最新 | 往期 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 以二进制形式打印浮点数 (johndcook.com) 5 分,由 ibobev 发布于 5 小时前 | 隐藏 | 往期 | 收藏 | 1 条评论 sheept 3 小时前 [–] 在 JavaScript 中,是 Math.PI.toString(2) 不知道 Python 或 JavaScript 的实现优化到了什么程度,但我想手动实现浮点数的二进制表示应该相对容易,因为你只需要取 1,后面跟上尾数的位,然后根据指数移动小数点即可。 回复 考虑申请 YC 2026 年秋季批次!申请截止日期为 7 月 27 日。 准则 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

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,

CAFEhex = 1100 1010 1111 1110two

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.921fb54442d18hex to binary by converting 1, 9, 2, etc. each to binary.

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

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

π = 11.001001000011111101101010100010001000010110100011000two

You could use Python’s bin() function to convert the fractional part, interpreted as an integer, to hex, though you may need to pad with 0 bits. For example,

>>> (1.03).hex()
'0x1.07ae147ae147bp+0

>>> bin(0x7ae147ae147)
'0b1111010111000010100011110101110000101000111'

The binary representation of 1.03ten is

1.000001111010111000010100011110101110000101000111two

We added a total of five zero bits, four for the 0 after the fractional point and one for converting 7 to 0111two.

联系我们 contact @ memedata.com