代码如下:
//字符串转字节,即用十进制表示的数字
let c1 = "青山大队长".to_owned().into_bytes();//也可以使用.as_bytes();
println!("{:?}",&c1);
//这里输出[233, 157, 146, 229, 177, 177, 229, 164, 167, 233, 152, 159, 233, 149, 191]
//十进制对应的数字转为字符
let num=vec![233, 157, 146, 229, 177, 177, 229, 164, 167, 233, 152, 159, 233, 149, 191];
let c2 = from_utf8(&num).unwrap(); //&num可以换为&c1
println!("{:?}",c2);//这里输出"青山大队长"
let c = hex::encode("青山大队长"); // 将&str转换为String
println!("{:?}",c);
//这里输出"e99d92e5b1b1e5a4a7e9989fe995bf"
let c3 = hex::decode("e99d92e5b1b1e5a4a7e9989fe995bf").unwrap(); // 将bites转换为Vec<u8>,得到的是十进制数字
println!("{:?}",c3);
//这里输出[233, 157, 146, 229, 177, 177, 229, 164, 167, 233, 152, 159, 233, 149, 191]
let c4 = from_utf8(&c3).unwrap(); //&num可以换为&c1
println!("{:?}",c4);
let c6 = "hello world".as_bytes();
println!("{:?}",c6);
let name = "青".to_string();
let mut name_in_binary = String::from("");
for character in name.clone().into_bytes() {
name_in_binary += &format!("-{:b} ", character);
}
println!("{} 的二进制码为: {}", name, name_in_binary);
以上功能代码输出的内容为:
[233, 157, 146, 229, 177, 177, 229, 164, 167, 233, 152, 159, 233, 149, 191]
"青山大队长"
"e99d92e5b1b1e5a4a7e9989fe995bf"
[233, 157, 146, 229, 177, 177, 229, 164, 167, 233, 152, 159, 233, 149, 191]
"青山大队长"
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
青 的二进制码为: -11101001 -10011101 -10010010