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

标签 algorithm rust binary

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

我有以下&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" 的函数。

提前致谢!

最佳答案

因为都是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)?)

关于algorithm - Rust:从二进制字符串表示形式转换为 ASCII 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63876919/

相关文章:

algorithm - 如何从文本中删除 OCR 伪像?

javascript - 多重约束复杂数据的最佳组合算法

java - Java中的前向链接和后向链接

rust - future.then() 如何返回一个 Future?

ruby - 在 ruby​​ 中定义二进制数的语法是什么?

c++ - 如何替换我的 'for' 循环以通过 STL mimax 算法查找最小值/最大值

rust - 为什么'static是impl的默认返回类型

binary - 串行通信吃传入的 ASCII DC1 字符

java - 如何将这个二进制乘法代码的答案转化为二进制?

error-handling - 传播不同错误类型的函数的结果类型的正确错误部分是什么?