Description
Location
Summary
The standard library of some programming languages has a method to get the number of bits in an integer:
bits.Len()
in Goint.bit_length()
in PythonInteger.bit_length
in Ruby
The number of bits in binary representation of a positive integer
$\lfloor \log_2 n \rfloor + 1$
Rust doesn't have a method like the above, but it does have ilog2
and checked_ilog2
. Therefore, we can get the number of bits in an integer by using ilog2
or checked_ilog2
as follows:
// n > 0
assert_eq!(42_u8.ilog2() + 1, 6);
// supports `n == 0`
assert_eq!(u8::MIN.checked_ilog2().map_or(0, |n| n + 1), 0);
// similar to Python's `int.bit_length()`
assert_eq!((-42_i8).unsigned_abs().ilog2() + 1, 6);
I don't think everyone knows that we can get the number of bits in an integer by this way.
Personally, I don't think there's any need to add a method like bits.Len()
and int.bit_length()
to integer types, since we can get the number of bits in an integer using
Therefore, I think it would be helpful to mention in the explanation of ilog2
and checked_ilog2
that the number of bits in an integer can be obtained by using
See also: Rust Internals