1

Why does the bit length of 0 return 0 and not 1?

>>> int(0).bit_length()
0

>>> int(2).bit_length()
2

2 in binary is 0x10 which represents two bits, doesn't zero in binary still techincally take up 1 bit since its representation in hex is 0x0?

APorter1031
  • 2,107
  • 6
  • 17
  • 38
  • These are theoretical bounds. In practice, all integers are represented by some number of bytes, so you could just as well ask why `bit_length()` doesn't always return a non-zero multiple of 8. – chepner Apr 05 '18 at 15:22

2 Answers2

2

The Python documentation states

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

Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35
  • But is there a rationale for special-casing 0? Is there some use case they know of or anticipate where this behavior is desired? Or did they go out of their way to be wrong? – ktb Apr 22 '22 at 15:59
0

Please read documentation on https://docs.python.org/3/library/stdtypes.html It is explained. That's how the function works. if you send it 0, it'll output 0

If x is zero, then x.bit_length() returns 0.

Weiner Nir
  • 1,435
  • 1
  • 15
  • 19