Reputation: 2256
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?
Upvotes: 1
Views: 1406
Reputation: 1475
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.
Upvotes: 0
Reputation: 3113
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
Upvotes: 2