Rust:将二进制字符串表示形式转换为ASCII字符串

时间:2020-09-14 01:00:35

标签: algorithm rust binary

我正在尝试将包含某些 ASCII 文本的二进制表示形式的String转换回 ASCII 文本。

我有以下&str

let binary: &str = "01010010 01110101 01110011 01110100 01100001 01100011 01100101 01100001 01101110 01110011";

我想将此&str转换为 ASCII 版本,即单词:“ Rustaceans”。

目前,我正在将该单词转换为二进制,如下所示:

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

我正在寻找要获取to_binary输出并返回"Rustaceans"的函数。

谢谢!

2 个答案:

答案 0 :(得分:2)

由于都是ASCII文本,因此可以使用u8::from_str_radix,该示例如下:

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更具可读性,如果要使用&str类型,请在下面将其用作转换器:

std::str::from_utf8(&decode_binary(binary)?)

答案 1 :(得分:1)

您可以使用str::splitu32::from_str_radix和(当前)不稳定的char::char_from_u32的简单组合:

#![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