I'm trying to convert a String which contains the binary representation of some ASCII text, back to the ASCII text.
I have the following &str:
let binary: &str = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";
And I want to convert this &str to the ASCII version, which is the word: "Rustaceans".
Currently I'm converting this word to binary as follows:
fn to_binary(s: &str) -> String {
let mut binary = String::default();
let ascii: String = s.into();
for character in ascii.clone().into_bytes() {
binary += &format!("0{:b} ", character);
}
// removes the trailing space at the end
binary.pop();
binary
}
Source
I'm looking for the function which will take the output of to_binary and returns "Rustaceans".
Thanks in advance!
Since all are ASCII texts, you can use u8::from_str_radix, the demo is below:
use std::{num::ParseIntError};
pub fn decode_binary(s: &str) -> Result<Vec<u8>, ParseIntError> {
(0..s.len())
.step_by(9)
.map(|i| u8::from_str_radix(&s[i..i + 8], 2))
.collect()
}
fn main() -> Result<(), ParseIntError> {
let binary: &str = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";
println!("{:?}", String::from_utf8(decode_binary(binary)?));
Ok(())
}
Playground
String::from is more readable, and in case you want &str type, use below as converter:
std::str::from_utf8(&decode_binary(binary)?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With