【问题标题】:Rust: Convert from a binary string representation to ASCII stringRust:从二进制字符串表示转换为 ASCII 字符串
【发布时间】:2020-12-31 17:44:55
【问题描述】:

我正在尝试将包含一些 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" 的函数。

提前致谢!

【问题讨论】:

  • 这听起来有点像课堂作业。
  • "寻找将获取 to_binary 的输出并返回 "Rustaceans" 的函数。" stdlib 中没有这样的函数,你必须去编写它(我希望这就是练习的全部重点)。

标签: algorithm rust binary


【解决方案1】:

由于都是ASCII文本,可以使用u8::from_str_radix,demo如下:

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 更具可读性,如果您想要&amp;str 类型,请使用以下转换器:

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

【讨论】:

    【解决方案2】:

    您可以使用 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

    【讨论】:

      猜你喜欢
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多