Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: Convert from a binary string representation to ASCII string

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!

like image 782
Esteban Borai Avatar asked Jan 31 '26 03:01

Esteban Borai


1 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)?)
like image 86
James Yang Avatar answered Feb 02 '26 23:02

James Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!