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