Are there functions to convert between a numerical value and a list of bits?

Are there any crates published on crates.io that provide functions to convert a numerical value to a list of bits, and vice versa?

Example for u8:

fn from_bits(bits: [u8; 8]) -> u8 {
    let mut v = 0;
    for (i, bit) in bits.iter().enumerate() {
        v |= bit << (7 - i);
    }
    v
}

fn to_bits(v: u8) -> [u8; 8] {
    let mut bits = [0; 8];
    for (i, bit) in bits.iter_mut().enumerate() {
        *bit = (v >> (7 - i)) & 1;
    }
    bits
}

assert_eq!(from_bits([0, 0, 0, 1, 0, 0, 1, 0]), 0b0001_0010_u8);
assert_eq!(to_bits(0b0001_0010_u8), [0, 0, 0, 1, 0, 0, 1, 0]);

I couldn't find any functions for this purpose in the standard library.

For what purpose do you want to work with “lists of bits”? It’s likely that there’s a better way that avoids having such a data structure at all, and if you write more about your use case, I might be able to suggest one.

The purpose is to process each pixel of the XBM image file format. This format stores a list of bytes containing information about eight pixels. Each pixel represents either white (0) or black (1).

Currently, I'm using bitwise operations to convert between 8 pixels and a byte. It would be a bit useful to have a function for this purpose. However, if there are no functions for the purpose, the current conversion methods using bitwise operations are fine.

1 Like

Sounds like a job for bitflags.

Or maybe something like bitvec?

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.