python bit_length() of 0 returns 意外值
python bit_length() of 0 returns unexpected value
为什么 0 return 的位长是 0 而不是 1?
>>> int(0).bit_length()
0
>>> int(2).bit_length()
2
2 在二进制中是 0x10,表示两位,二进制中的零在技术上仍然占用 1 位,因为它在十六进制中的表示是 0x0?
Python 文档指出
More precisely, if x is nonzero, then x.bit_length() is the unique
positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently,
when abs(x) is small enough to have a correctly rounded logarithm,
then k = 1 + int(log(abs(x), 2)).
If x is zero, then x.bit_length()
returns 0.
https://docs.python.org/3/library/stdtypes.html#int.bit_length
请阅读 https://docs.python.org/3/library/stdtypes.html 上的文档
它被解释。
这就是该功能的工作原理。如果你发送 0,它会输出 0
If x is zero, then x.bit_length() returns 0.
为什么 0 return 的位长是 0 而不是 1?
>>> int(0).bit_length()
0
>>> int(2).bit_length()
2
2 在二进制中是 0x10,表示两位,二进制中的零在技术上仍然占用 1 位,因为它在十六进制中的表示是 0x0?
Python 文档指出
More precisely, if x is nonzero, then x.bit_length() is the unique positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x) is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2)).
If x is zero, then x.bit_length() returns 0.
https://docs.python.org/3/library/stdtypes.html#int.bit_length
请阅读 https://docs.python.org/3/library/stdtypes.html 上的文档 它被解释。 这就是该功能的工作原理。如果你发送 0,它会输出 0
If x is zero, then x.bit_length() returns 0.