Hi internals,
Currently, the number of bits necessary to represent an integer in binary to can be obtained by:
For unsigned integers:
let answer: u16 = 42; // 0b10_1010
assert_eq!(answer.checked_ilog2().map_or(0, |n| n + 1), 6);
For signed integers (excluding the sign bit and leading zeros):
let n: i16 = -37; // -0b10_0101
assert_eq!(n.unsigned_abs().checked_ilog2().map_or(0, |n| n + 1), 6);
Methods for this purpose appear to exist in the standard library of several languages:
int.bit_length()
in Pythonbits.Len()
in GoInteger.bit_length
in Ruby
The above methods can achieve the goal, but I think they are a bit complicated.
I think there is some demand for this, so it would be useful to have methods for this purpose.
For unsigned integers:
assert_eq!(u16::MIN.bit_len(), 0); // 0b0
assert_eq!(1_u16.bit_len(), 1); // 0b1
assert_eq!(42_u16.bit_len(), 6); // 0b10_1010
assert_eq!(u16::MAX.bit_len(), 16); // 0b1111_1111_1111_1111
For signed integers, returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros (-37
is considered 37
), similar to Python's int.bit_length()
:
assert_eq!(i16::MIN.bit_len(), 16); // -0b1000_0000_0000_0000
assert_eq!((-37_i16).bit_len(), 6); // -0b10_0101
assert_eq!((-1_i16).bit_len(), 1); // -0b1
assert_eq!(i16::default().bit_len(), 0); // 0b0
assert_eq!(1_i16.bit_len(), 1); // +0b1
assert_eq!(37_i16.bit_len(), 6); // +0b10_0101
assert_eq!(i16::MAX.bit_len(), 15); // +0b111_1111_1111_1111
Comments to this suggestion are welcome.
Thanks.