Skip to content

Instantly share code, notes, and snippets.

@Konard
Last active December 14, 2022 13:43
Show Gist options
  • Save Konard/26a49ef002f7f56de721b9919f85448b to your computer and use it in GitHub Desktop.
Save Konard/26a49ef002f7f56de721b9919f85448b to your computer and use it in GitHub Desktop.
A solution to split bytes into 7 bit chunks by ChatGPT
We split bytes [0b1101_0101, 0b1010_1010] into 7 bit chunks like this [0b0101_0101, 0b0101_0101, 0b0000_0010]
Make a function in rust for any number of bytes.
fn split_bytes_into_7bit_chunks(bytes: &[u8]) -> Vec<u8> {
let mut chunks = Vec::new();
let mut buffer: u16 = 0;
let mut buffer_size = 0;
for byte in bytes {
buffer |= (*byte as u16) << buffer_size;
buffer_size += 8;
while buffer_size >= 7 {
chunks.push((buffer & 0b0111_1111) as u8);
buffer >>= 7;
buffer_size -= 7;
}
}
// If there are remaining bits in the buffer, add a final chunk
if buffer_size > 0 {
chunks.push((buffer & 0b0111_1111) as u8);
}
chunks
}
fn main() {
let bytes = [0b1101_0101, 0b1010_1010];
let chunks = split_bytes_into_7bit_chunks(&bytes);
assert_eq!(chunks, [0b0101_0101, 0b0101_0101, 0b0000_0010]);
let bytes = [0b1000_0000];
let chunks = split_bytes_into_7bit_chunks(&bytes);
assert_eq!(chunks, [0b0000_0000, 0b0000_0001]);
let bytes = [0b0000_0000];
let chunks = split_bytes_into_7bit_chunks(&bytes);
assert_eq!(chunks, [0b0000_0000, 0b0000_0000]);
let bytes = [0b0111_1111, 0b1111_1111];
let chunks = split_bytes_into_7bit_chunks(&bytes);
assert_eq!(chunks, [0b0111_1111, 0b0111_1110, 0b0000_0011]);
let bytes = [0b0111_1111, 0b1111_1111, 0b0111_1110];
let chunks = split_bytes_into_7bit_chunks(&bytes);
assert_eq!(chunks, [0b0111_1111, 0b0111_1110, 0b0111_1011, 0b0000_0011]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment