From 4c00c14258e4f8905ee4a2595809747b722dd957 Mon Sep 17 00:00:00 2001 From: Dukantic Date: Tue, 8 Apr 2025 17:33:52 +0200 Subject: [PATCH] binary to tree --- src/byte_writer.rs | 14 ++++++-------- src/node.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/byte_writer.rs b/src/byte_writer.rs index 69c1d65..a2f3afa 100644 --- a/src/byte_writer.rs +++ b/src/byte_writer.rs @@ -31,20 +31,18 @@ pub fn string_to_binary(bits: &str) -> Vec { pub fn binary_to_string(bytes: Vec, len: u8) -> String { let mut binary = String::new(); //bytes.reverse(); - let mut word = Vec::new(); + let mut word = String::new(); for b in &bytes { - let mut current = *b; - while current != 0b0000_0000 { - if current % 2 == 1 { + let current = *b; + for i in 0..8 { + if current >> (7 - i) & 1 == 1 { word.push('1'); } else { word.push('0'); } - current >>= 1; } - word.reverse(); - binary = binary + &word.iter().collect::(); - word = Vec::new(); + binary = binary + &word; + word = String::new(); } for _ in 0..8 - len { binary.pop(); diff --git a/src/node.rs b/src/node.rs index 1ddf5dd..4c7bca4 100644 --- a/src/node.rs +++ b/src/node.rs @@ -41,3 +41,29 @@ pub fn create_tree(mut nodes: Vec) -> Node { } nodes.pop().unwrap() } + +pub fn read_tree(binary: &str) -> Node { + let mut stack = String::from(binary); + let mut to_do: Vec<&mut Box> = Vec::new(); + let mut root = Box::new(Node::new()); + + if stack.remove(0) == '1' { + to_do.push(&mut root); + } else { + return *root; + } + + while !to_do.is_empty() { + let mut int_root = to_do.remove(0); + let mut l = Box::new(Node::new()); + let mut r = Box::new(Node::new()); + if stack.remove(0) == '1' { + int_root.l = Some(l); + to_do.push(int_root.l.as_mut().unwrap()); + } + if stack.remove(0) == '1' { + to_do.push(int_root.r.as_mut().unwrap()); + } + } + *root +}