我正在尝试将包含某些 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
}
我正在寻找将获取 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(())
}
String::from
更具可读性,如果您需要 &str
类型,请使用下面的转换器:
std::str::from_utf8(&decode_binary(binary)?)
关于algorithm - Rust:从二进制字符串表示形式转换为 ASCII 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63876919/