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

Viewed 242

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.

2 Answers

You can use the bitflags crate to use bits as bools stored in different sizes. Although it is intended for other uses, you can still leverage its functionality for it.

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);
}
Related