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
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
Discussion
実は各種整数型には
.leading_zeros()というメソッドがあるため,これを型のビット長から引くと 2 進法の桁数が得られます.あと,
vがゼロでないと分かっていれば,(現在 unstable ですが).log2()も使えます.ありがとうございます!
leading_zeros を使うこちらのほうがスマートで log2 は理想的ですね
勉強になります
0の桁数も考えていませんでした