Skip to content

Add mention that ilog2 and checked_ilog2 can be used to get the number of bits in an integer #133101

Open
@sorairolake

Description

@sorairolake

Location

Summary

The standard library of some programming languages has a method to get the number of bits in an integer:

The number of bits in binary representation of a positive integer $n$ is the integer part of $1 + \log_2 n$, i.e.

$\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 $\lfloor \log_2 n \rfloor + 1$. However, since the standard library of some programming languages has a method to get the number of bits in an integer, I think this is a feature that is in some demand.

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 $\lfloor \log_2 n \rfloor + 1$.

See also: Rust Internals

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions