Rust: Convert from a binary string representation to ASCII string

Viewed 2607

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 Answers

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)?)

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

Related