【问题标题】:C# coding: hexadecimal to decimal & character encodingC#编码:十六进制转十进制和字符编码
【发布时间】:2014-01-22 09:43:17
【问题描述】:

下面是我正在尝试解决的代码(十六进制到十进制的转换).. 我发现错误出现在我在代码中注释的地方..

请提供解决方案以纠正..

static void Main(string[] args)
    {

        byte[] byteData;
        int n;
        byteData = GetBytesFromHexString("001C0014500C0A5B06A4FFFFFFFFFFFFFFFFFFFFFFFFFFFF");
        n = byteData.Length;
        Console.WriteLine(n);
        string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n);   //error
        Console.WriteLine(s);
        Console.ReadLine();
    }

    public static byte[] GetBytesFromHexString(string hexString)
    {
        //MessageBox.Show("getbytes ");
        if (hexString == null)
            return null;

        if (hexString.Length % 2 == 1)
            hexString = '0' + hexString; // Up to you whether to pad the first or last byte

        byte[] data = new byte[hexString.Length / 2];

        for (int i = 0; i < data.Length; i++)
        {
            data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            Console.WriteLine(data[i]);
        }

我得到的输出是: “\0\0P\f\n[����������������” 转换后的十进制值未编码。

更新: 预期输出为“0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255”

【问题讨论】:

  • 您希望Console.WriteLine(s); 的输出是什么?
  • 我得到了未编码的 System.Byte[] ..
  • 代码完美运行:提供十六进制数字的字符串,将其转换为字节数组(data[0] = 0,data[1] = 0x1c = 28 等),转换字节数组到一个字符串(假设数组包含UTF8)一个显示它。因为十六进制字符串包含一些无法显示的字符(例如 0x1C、0x14 和 0xFF),所以输出看起来很奇怪,但并非不正确。所以,@MaxYakimets 的问题仍然存在:你期待什么?
  • @venerik 谢谢你的回复.. 从我得到的方法返回数据作为 System.Byte [] wen 它转换为字符串我得到那个输出.. 请帮助我

标签: c# string hex


【解决方案1】:

代替

string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n);

string s = String.Join(" ", byteData);

【讨论】:

  • 我得到的输出是 System.Byte[].. 在方法中数据正在返回 System.Byte[].. 我仍然没有得到输出..
  • @user3222857 您接受了答案,但评论说您没有得到输出。如果您仍需要帮助,请说明您当前的状态。
  • 谢谢我得到了输出..我仍然怀疑 string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n);为什么这段代码不起作用??
  • 因为“a number 0”和“a character 0”不一样:数字0在内存中保存为0,而UTF8字符“0”在内存中保存为48(30十六进制,即 0x30) :) byte[] zero = Encoding.UTF8.GetBytes("0");
【解决方案2】:

您可以使用它并尝试使用基数(在本例中为 2 )。这个我曾经写过的sn-p,一直在帮助我。

 private void ConvHexStringToBitString(ref string strErrorBitMask)
    {
        try
        {
            string strTempStr = strErrorBitMask;
            if (strTempStr != string.Empty)
            {
                strTempStr = Convert.ToString(Convert.ToInt32(strTempStr.Replace(" ", "0"), 16), 2);
            }
            strErrorBitMask = strTempStr.PadLeft(32, '0');

        }
        catch (Exception ex)
        {
            LogWithMsg(ex);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2016-04-17
    • 2019-11-22
    • 2012-06-26
    • 2020-06-15
    • 2013-06-10
    相关资源
    最近更新 更多