Search code examples
memory-managementrustbytebit

How to write/read 8 true/false in a single byte on rust language


Everyone knows that bool uses 1 byte and not 1 bite.

In case I want to store 8 (or more) true/false in a single byte, how can I do it on Rust?

Something like this:

fn main()
{
   let x:ByteOnBits;
   x[3]=true;
   if x[4]
   {
      println!("4th bit is true");
   }
}

an array of 8 bools would be 8 bytes, not 1 byte as I am expecting.


Solution

  • The bitvec crate provides facilities of the kind you're asking for:

    use bitvec::prelude::*;
    
    fn main() {
        let mut data = 0u8;
        let bits = data.view_bits_mut::<Lsb0>();
        bits.set(3, true);
        if bits[4] {
            println!("xxx");
        }
        assert_eq!(data, 8);
    }