bit_combi_iter

Crates.iobit_combi_iter
lib.rsbit_combi_iter
version1.0.2
sourcesrc
created_at2021-09-07 13:53:14.95182
updated_at2021-09-15 11:06:02.855577
descriptionAn iterator to iterate all bit combinations less than given unsigned integer
homepagehttps://github.com/rhysd/bit_combi_iter#readme
repositoryhttps://github.com/rhysd/bit_combi_iter
max_upload_size
id447999
size12,180
Linda_pp (rhysd)

documentation

https://docs.rs/bit_combi_iter

README

bit_combi_iter

crates.io CI

bit_combi_iter is a small dependency-free crate to enumerate all bit combinations less than given unsigned integer value keeping 1s in the bits.

use bit_combi_iter::BitCombinations;

fn main() {
    let u = 0b00010100u8;

    let mut c = BitCombinations::new(u);

    println!("{:#b}", c.next().unwrap()); // => 0b00010010
    println!("{:#b}", c.next().unwrap()); // => 0b00010001
    println!("{:#b}", c.next().unwrap()); // => 0b00001100
    println!("{:#b}", c.next().unwrap()); // => 0b00001010
    println!("{:#b}", c.next().unwrap()); // => 0b00001001
    println!("{:#b}", c.next().unwrap()); // => 0b00000110
    println!("{:#b}", c.next().unwrap()); // => 0b00000101
    println!("{:#b}", c.next().unwrap()); // => 0b00000011
    println!("{}", c.next().is_none()); // => true
}

This crate is useful when you want to enumerate all n bit integers including k ones.

// Enumerate all 5 bit integers including 3 ones (as u8)
BitCombinations::new(0b11100u8)
// 11100
// 11010
// 11001
// 10110
// 10101
// ...

Install

Add this crate to dependencies in your Cargo.toml.

[dependencies]
bit_combi_iter = "1"

Document

See the API document.

Special Thanks

The algorithm was borrowed from the blog post by @herumi.

License

Distributed under the MIT License.

Commit count: 27

cargo fmt