How to convert binary code to text in Rust

1 Answer

0 votes
fn bin_to_text(bin_txt: &str) -> String {
    let mut text = String::new();

    // Iterate over the binary string in chunks of 8 bits
    for chunk in bin_txt.as_bytes().chunks(8) {
        // Convert each 8-bit chunk to a string slice
        let binary_chunk = std::str::from_utf8(chunk).unwrap();

        // Convert the binary chunk to a decimal integer
        let ascii_value = u8::from_str_radix(binary_chunk, 2).unwrap();

        // Convert the integer to a character and append to the result
        text.push(ascii_value as char);
    }

    text
}

fn main() {
    let binary_input = "0101000001110010011011110110011101110010011000010110110101101101011010010110111001100111";
    
    let text_output = bin_to_text(binary_input);

    println!("{}", text_output);
}



/*
run:

Programming

*/

 



answered Apr 14 by avibootz

Related questions

1 answer 52 views
1 answer 103 views
103 views asked Oct 2, 2022 by avibootz
1 answer 123 views
1 answer 104 views
104 views asked May 2, 2023 by avibootz
2 answers 105 views
1 answer 31 views
1 answer 34 views
...