在Julia中如何将字节向量转换为字符串?
将字节类型Vector转换为字符串
下面针对几种主流编程语言,给出将字节数组(Vector)转换为对应字符串的实现方式,兼容ASCII及UTF-8编码的非ASCII字符:
Python
Python中可直接使用bytes类型的decode()方法,指定编码为utf-8(UTF-8兼容ASCII,两种场景通用):
# ASCII字节数组转换 ascii_bytes = [0x61, 0x62, 0x63, 0x64, 0x65] ascii_str = bytes(ascii_bytes).decode('utf-8') print(ascii_str) # 输出: abcde # UTF-8中文字节数组转换 chinese_bytes = [0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd] chinese_str = bytes(chinese_bytes).decode('utf-8') print(chinese_str) # 输出: 你好
Rust
Rust中Vec<u8>可通过String::from_utf8()方法转换为字符串,该方法返回Result<String, FromUtf8Error>,非法UTF-8字节会返回错误;需容错处理时可用String::from_utf8_lossy():
fn main() { // ASCII字节数组转换 let ascii_bytes = vec![0x61, 0x62, 0x63, 0x64, 0x65]; let ascii_str = String::from_utf8(ascii_bytes).unwrap(); println!("{}", ascii_str); // 输出: abcde // UTF-8中文字节数组转换 let chinese_bytes = vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd]; let chinese_str = String::from_utf8(chinese_bytes).unwrap(); println!("{}", chinese_str); // 输出: 你好 }
Java
Java中使用String类构造方法,指定StandardCharsets.UTF_8编码即可:
import java.nio.charset.StandardCharsets; public class ByteToString { public static void main(String[] args) { // ASCII字节数组转换 byte[] asciiBytes = {0x61, 0x62, 0x63, 0x64, 0x65}; String asciiStr = new String(asciiBytes, StandardCharsets.UTF_8); System.out.println(asciiStr); // 输出: abcde // UTF-8中文字节数组转换 byte[] chineseBytes = {(byte)0xe4, (byte)0xbd, (byte)0xa0, (byte)0xe5, (byte)0xa5, (byte)0xbd}; String chineseStr = new String(chineseBytes, StandardCharsets.UTF_8); System.out.println(chineseStr); // 输出: 你好 } }
内容的提问来源于stack exchange,提问作者Josep Espasa
相关产品推荐
相关产品推荐

