binary to tree
This commit is contained in:
@@ -31,20 +31,18 @@ pub fn string_to_binary(bits: &str) -> Vec<u8> {
|
|||||||
pub fn binary_to_string(bytes: Vec<u8>, len: u8) -> String {
|
pub fn binary_to_string(bytes: Vec<u8>, len: u8) -> String {
|
||||||
let mut binary = String::new();
|
let mut binary = String::new();
|
||||||
//bytes.reverse();
|
//bytes.reverse();
|
||||||
let mut word = Vec::new();
|
let mut word = String::new();
|
||||||
for b in &bytes {
|
for b in &bytes {
|
||||||
let mut current = *b;
|
let current = *b;
|
||||||
while current != 0b0000_0000 {
|
for i in 0..8 {
|
||||||
if current % 2 == 1 {
|
if current >> (7 - i) & 1 == 1 {
|
||||||
word.push('1');
|
word.push('1');
|
||||||
} else {
|
} else {
|
||||||
word.push('0');
|
word.push('0');
|
||||||
}
|
}
|
||||||
current >>= 1;
|
|
||||||
}
|
}
|
||||||
word.reverse();
|
binary = binary + &word;
|
||||||
binary = binary + &word.iter().collect::<String>();
|
word = String::new();
|
||||||
word = Vec::new();
|
|
||||||
}
|
}
|
||||||
for _ in 0..8 - len {
|
for _ in 0..8 - len {
|
||||||
binary.pop();
|
binary.pop();
|
||||||
|
|||||||
26
src/node.rs
26
src/node.rs
@@ -41,3 +41,29 @@ pub fn create_tree(mut nodes: Vec<Node>) -> Node {
|
|||||||
}
|
}
|
||||||
nodes.pop().unwrap()
|
nodes.pop().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn read_tree(binary: &str) -> Node {
|
||||||
|
let mut stack = String::from(binary);
|
||||||
|
let mut to_do: Vec<&mut Box<Node>> = 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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user