【问题标题】:C# how convert a string hex value in "bin" like xxdC#如何在“bin”中转换字符串十六进制值,如xxd
【发布时间】:2017-09-09 06:44:35
【问题描述】:

我正在尝试将字符串十六进制值转换为“二进制”(.bin) 格式的解决方案, 比如 xxd 命令。

示例: 我有一个字符串 hexValue "17c7dfef853adcddb2c4b71dd8d0b3e3363636363"

在 linux 上,我想要一个类似下一个的结果:

echo "hexvalue" > file.hex cat 文件.hex | xxd -r -p > 文件.bin

file.bin 的 hexdump 给出:

0000000 17 c7 df ef 85 3a dc dd b2 c4 b7 1d d8 d0 b3 e3

0000010 36 36 36 36 36 36 36

我的转换程序是:

Private static string convertHex(string value)
{
    string[] hexVal = value.Split(' ');
    StringBuilder s = new StringBuilder();

    foreach (string hex in hexVal)
    {
         int val = Convert.ToInt32(hex, 16);
         string stringValue = char.ConvertFromUtf32(val);
         s.Append(stringValue);
    }
    return s.ToString();
}

string MyString = "17 c7 df ef 85 3a dc dd b2 c4 b7 1d d8 d0 b3 e3 36 36 36 36 36";
string newString = converthex(MyString);
Console.WriteLine(newString);
File.WriteAllText("file2.bin", newString);

所以现在,当查看 file2.bin 的 hexdump 时,我看到了:

0000000 17 c3 87 c3 97 c3 af c2 85 3a c3 9c c3 9d c2 b2

0000010 c3 84 c2 b7 1d c3 98 c3 90 c2 b3 a3 36 36 36

为什么我的新文件中存在 c3 或 c2 ? 你有解决办法吗?

感谢您的帮助!

【问题讨论】:

    标签: c# binary hexdump


    【解决方案1】:

    File.WriteAllText 用于文本文件写入,它以 UTF-8 编码传递的字符串。这就是输出文件中出现额外字节的原因。

    您想要的效果表明您需要一个二进制文件,而无需在进程中转换为 UTF-32 字符串。这是工作版本的示例:

    class Program
    {
        private static byte[] convertHex(string value)
        {
            string[] hexVal = value.Split(' ');
            byte[] output = new byte[hexVal.Length];
            var i = 0;
            foreach (string hex in hexVal)
            {
                byte val = (byte)(Convert.ToInt32(hex, 16));
                output[i++] = val;
            }
            return output;
        }
        static void Main(string[] args)
        {
            string MyString = "17 c7 df ef 85 3a dc dd b2 c4 b7 1d d8 d0 b3 e3 36 36 36 36 36";
            var file = new FileStream("file2.bin", FileMode.Create);
            var byteArray = convertHex(MyString);
            file.Write(byteArray, 0, byteArray.Length);
        }
    }
    

    【讨论】:

    • 嗯,好吧,这是我的错误。我的程序必须计算十六进制字符串中的md5sum;以二进制格式。但是,我没有看到,我的函数 md5 它是用 utf8.getstring 调用的。好的,很好,有你的帮助。谢谢你。这一天……天哪!!
    猜你喜欢
    • 2015-10-30
    • 2016-08-07
    • 2019-07-27
    • 2015-06-15
    • 1970-01-01
    • 2015-02-06
    • 2011-07-11
    • 2013-02-07
    • 2018-01-31
    相关资源
    最近更新 更多