You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将十六进制输入编码为Unicode并写入文件?现有代码无法运行

解决十六进制转Unicode字符并写入文件的问题

嘿,我来帮你捋捋这个问题哈~你输入十六进制394A想得到字符9J写入文件,但现有代码跑不起来,主要是这几个问题:

现有代码的坑

  • 变量未定义:代码里的uni完全没给出定义,编译器根本不知道它是啥,这肯定会报错。
  • 逻辑不对:就算uni是正确的内容,你调用StrToUni(uni.ToString())后只写入前2个字节,而UTF-16编码下每个字符占2字节,这只能写出一个字符,根本得不到9J两个字符。
  • 转换步骤缺失:你跳过了「十六进制字符串解析成对应字节/字符」的关键步骤,直接对未知变量转字符串再编码,方向就错了。

正确的实现方式

根据你的需求(十六进制394A转成9J写入文件),分两种场景给你代码:

场景1:直接写入对应ASCII字节(文件用普通文本打开显示9J)

这个场景下,39对应ASCII字符9,4A对应J,直接把十六进制转成字节写入就行:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string hexInput = "394A";
        byte[] targetBytes = HexToByteArray(hexInput);
        
        using (FileStream fsDest = new FileStream("output.txt", FileMode.Create))
        {
            fsDest.Write(targetBytes, 0, targetBytes.Length);
        }
    }

    // 把十六进制字符串转成字节数组的辅助方法
    private static byte[] HexToByteArray(string hex)
    {
        byte[] bytes = new byte[hex.Length / 2];
        for (int i = 0; i < hex.Length; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }
        return bytes;
    }
}

场景2:用Unicode(UTF-16)编码写入文件

如果必须用UTF-16编码,那9J对应的UTF-16小端字节是0x39 0x00 0x4A 0x00,代码可以这么写:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string targetStr = "9J";
        Encoding unicode = Encoding.Unicode; // UTF-16小端编码
        byte[] unicodeBytes = unicode.GetBytes(targetStr);
        
        using (FileStream fsDest = new FileStream("output.txt", FileMode.Create))
        {
            fsDest.Write(unicodeBytes, 0, unicodeBytes.Length);
        }
    }
}

为啥你的代码不行?

再啰嗦两句:你原来的代码里,uni是凭空出现的,没有从十六进制字符串转换的过程;而且只写2个字节,最多只能输出一个UTF-16字符,自然得不到你要的9J。按照上面的代码来,就能正常生成你想要的文件啦~

内容的提问来源于stack exchange,提问作者user2729463

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:49:34