3

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!

2
  • 5
    This smells suspiciously like a class assignment. Commented Sep 14, 2020 at 2:50
  • 1
    "looking for the function which will take the output of to_binary and returns "Rustaceans"." there is no such function in the stdlib, you have to go and write it (and I rather expect that's the entire point of the exercise). Commented Sep 14, 2020 at 6:35

2 Answers 2

3

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)?)
Sign up to request clarification or add additional context in comments.

Comments

1

There a simple combination of str::split, u32::from_str_radix and the (currently) unstable char::char_from_u32 that you can use for this:

#![feature(assoc_char_funcs)]

fn bin_str_to_word(bin_str: &str) -> String {
    bin_str.split(" ")
    .map(|n| u32::from_str_radix(n, 2).unwrap())
    .map(|c| char::from_u32(c).unwrap())
    .collect()
}

fn main() {
    let binary: &str = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";
    let word : String = bin_str_to_word(binary);
    println!("{}", word);
}

Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.