rust学习-utf8 和 utf16 互转, 保存utf16格式文件

rust学习-UTF8 和 UTF16 互转, 保存utf16格式文件

读取 UTF16 格式文件, UTF8 和 UTF16 互转

    //UTF16 有大端小端的格式,这里是小端的例子
    let bytes = fs::read("UTF16_LE.txt").unwrap();

    //将读出来的 Vec<u8> 的字节序 存储到 Vec<u16>
    let utf16_vec: Vec<u16> = bytes
        .chunks(2)
        .map(|b| u16::from_le_bytes([b[0], b[1]]))
        .collect();

    //将 UTF16 转成 UTF8
    let mut buf = String::from_utf16(&utf16_vec[..]).unwrap();

    /*
     ...
     ...
     ...
    */

    let writer = Vec::new();
    let s: String = String::from_utf8_lossy(&writer).to_string();

    //转成 UTF16
    let s: Vec<u16> = s.encode_utf16().collect();
    let mut file = fs::File::create("test.ini").unwrap();
    
    //写入文件
    for i in 0..s.len() {
        file.write_all(&s[i].to_le_bytes()).unwrap();
    }
posted @   blackTree  阅读(409)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示