Search code examples
rustrust-cargo

How can I get bit value at positioned index in Rust?


I am trying to execute the below program.

fn main() {
    let a: u8 = 0b00000001;
    let b: u8 = 0b10101010;
    let c: u8 = 0b00001111;
    let length = a.count_ones() + a.count_zeros();
    for n in 0..length {
        println!("{}", a[n]);
        println!("{}", b[n]);
        println!("{}", c[n]);
    }
}

But I am getting error[E0608]: cannot index into a value of type `u8`


Solution

  • Rust doesn't provide indexes into individual bits of an integer. You need to use bitwise operators instead:

    This will count from the right (least to most significant bits):

    fn main() {
        let a: u8 = 0b00000001;
        let b: u8 = 0b10101010;
        let c: u8 = 0b00001111;
        let length = a.count_ones() + a.count_zeros();
        for n in 0..length {
            println!("{}", a >> n & 1);
            println!("{}", b >> n & 1);
            println!("{}", c >> n & 1);
        }
    }
    

    The reason why this isn't provided is that the Index trait is defined like this:

    pub trait Index<Idx>
    where
        Idx: ?Sized,
    {
        type Output: ?Sized;
        fn index(&self, index: Idx) -> &Self::Output;
    }
    

    index() returns a reference, but references are always to a byte address; you can't make a reference to a single bit.


    Depending on your actual use case, you may also be interested in one of these crates: