I don't think there is a way to do that with just the built-in std
library.
With the excellent bit-vec crate, though:
use bit_vec::BitVec;
fn main() {
let mut a = [false; 160];
a[42] = true;
let bitvec: BitVec = a.into_iter().collect();
let b: [u8; 20] = bitvec.to_bytes().try_into().unwrap();
println!("{:?}", b);
}
[0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
You can put it inside a generic function, but that requires nightly and unstable features:
#![feature(generic_const_exprs)]
use bit_vec::BitVec;
fn convert_vector<const N: usize>(bits: [bool; N]) -> [u8; N / 8] {
let bitvec: BitVec = bits.into_iter().collect();
bitvec.to_bytes().try_into().unwrap()
}
fn main() {
let mut a = [false; 160];
a[42] = true;
println!("{:?}", convert_vector(a));
}