iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Finding the number of binary digits in Rust

に公開2件

This is a function to get the result as a usize.

Closure version

let blen = |v: u64| -> usize { format!("{:b}", v).to_string().len() };

fn version

fn blen(v: i64) -> usize {
    format!("{:b}", v).to_string().len()
}
blen(100)
// 7
blen(0b0000111100001111)
// 12
GitHubで編集を提案

Discussion

とがとが

実は各種整数型には .leading_zeros() というメソッドがあるため,これを型のビット長から引くと 2 進法の桁数が得られます.

fn blen(v: i64) -> u32 {
    64 - v.leading_zeros()
}

あと,v がゼロでないと分かっていれば,(現在 unstable ですが).log2() も使えます.

#![feature(int_log)]

fn blen(v: i64) -> u32 {
    v.log2() + 1
}
1
anozonanozon

ありがとうございます!
leading_zeros を使うこちらのほうがスマートで log2 は理想的ですね
勉強になります
0の桁数も考えていませんでした