Skip to main content

crypt_tool/
binary_converter.rs

1use std::array::from_fn;
2
3pub struct BytesBitsConverter {
4    byte_to_bits_map: [[u8; 8]; 256],
5}
6
7impl Default for BytesBitsConverter {
8    fn default() -> Self {
9        Self::new()
10    }
11}
12
13impl BytesBitsConverter {
14    pub fn new() -> Self {
15        Self {
16            byte_to_bits_map: from_fn(|byte| from_fn(|idx| ((byte as u8 >> (7 - idx)) & 1))),
17        }
18    }
19
20    pub fn bytes_to_bits(&self, bytes1: &[u8]) -> Vec<u8> {
21        bytes1
22            .iter()
23            .flat_map(|byte1| self.byte_to_bits_map[*byte1 as usize])
24            .collect::<Vec<u8>>()
25    }
26
27    pub fn bits_to_bytes(&self, bin1: &[u8]) -> Vec<u8> {
28        bin1.chunks(8)
29            .map(|chunk| {
30                chunk
31                    .iter()
32                    .enumerate()
33                    .fold(0, |acc, (i, &bit)| acc | (bit << (7 - i)))
34            })
35            .collect::<Vec<u8>>()
36    }
37}