3

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.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
  • Bools aren't 1 bit, while they do (basically) represent either a 1 or a 0, so it technically only takes 1 bit to store it, almost every language stores it as an entire byte. There isn't any noticeable memory savings or performance improvements by making it so. Check out [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6abff46b6a2e9ad527328e99a2559d88) Rust playground showing how large a bool is (1, byte) – MindSwipe Jan 13 '22 at 21:27

2 Answers2

2

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.

Netwave
  • 40,134
  • 6
  • 50
  • 93
1

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);
}
user4815162342
  • 141,790
  • 18
  • 296
  • 355