crypt_tool/
binary_converter.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::array::from_fn;


pub struct BytesBitsConverter {
    byte_to_bits_map: [[u8; 8]; 256],
}

impl BytesBitsConverter {
    pub fn new() -> Self {
        Self {
            byte_to_bits_map: from_fn(|byte| {
                from_fn(|idx| ((byte as u8 >> (7 - idx)) & 1))
            })
        }
    }


    pub fn bytes_to_bits(&self, bytes1: &[u8]) -> Vec<u8> {
        bytes1.iter().flat_map(
            |byte1| self.byte_to_bits_map[*byte1 as usize]).collect::<Vec<u8>>()
    }

    pub fn bits_to_bytes(&self, bin1: &[u8]) -> Vec<u8> {
        bin1.chunks(8).map(|chunk| {
            chunk.iter().enumerate().fold(0, |acc, (i, &bit)| {
                acc | (bit << (7 - i))
            })
        }).collect::<Vec<u8>>()
    }
}