reverse_bits And Ones Trailing Counts
Mirror a whole integer with reverse_bits and probe bit patterns with count_zeros, leading_ones, and trailing_ones — count_ones + count_zeros stays fixed at 8.
Code
fn main() {
let v: u8 = 0b1011_0100;
// reverse_bits:全部 8 位镜像,高位变低位
println!("reversed: {:#010b}", v.reverse_bits());
// count_zeros:0 的个数 = 位宽 - 1 的个数
println!("ones {} zeros {}", v.count_ones(), v.count_zeros());
// leading_ones / trailing_ones:从前导/尾随方向数连续的 1
println!("leading ones: {}", 0b1110_0011u8.leading_ones());
println!("trailing ones: {}", 0b1110_0011u8.trailing_ones());
// count_ones + count_zeros 恒等于位宽:0b1110_0011 是 5 + 3 == 8
println!("{} + {} == 8", 0b1110_0011u8.count_ones(), 0b1110_0011u8.count_zeros());
// 全 1 / 全 0 的边界值
println!("all ones leading: {}", u8::MAX.leading_ones());
println!("all zeros trailing ones: {}", 0u8.trailing_ones());
// reverse_bits 自反:翻转两次回到原值
println!("double reverse: {}", v.reverse_bits().reverse_bits() == v);
}Counting runs of ones
Under the hood: the function main.
Points of care
- Every method is defined on u8 itself — no crates, no imports.
Using it
The whole walkthrough sits in fn main()
The run emits 7 labeled sections — reversed:, ones, leading ones:, trailing ones:, all ones leading:, all zeros trailing ones:, double reverse: — one per step.
Bit tools under test
let v: u8 = 0b1011_0100;
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- What does reverse_bits And Ones Trailing Counts print when run?
- Execute the whole file; each printed line is prefixed with a label like `reversed:`, `ones`, `leading ones:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.