简体   繁体   English

C#编码:十六进制到十进制和字符编码

[英]C# coding: hexadecimal to decimal & character encoding

Below is the code(conversion of hexadecimal to decimal) I'm trying to work out .. I found error which appears in place I've commented in the code.. 下面是代码(十六进制到十进制的转换),我正在尝试解决..我发现了错误,该错误出现在代码中已注释的位置。

Please provide a solution to rectify .. 请提供解决方案以纠正..

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]);
        }

What I'm getting as output is: "\\0\\0P\\f\\n[ " The converted decimal value is not been encoded. 我得到的输出是:“ \\ 0 \\ 0P \\ f \\ n [ ”“转换后的十进制值未编码。

UPDATE: Expected output is "0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255" 更新:预期的输出是“ 0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255”

Instead of 代替

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

write

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

You can use this and try to play with the radix ( in this case 2 ). 您可以使用它并尝试使用基数(在这种情况下为2)。 This snippet, which I once wrote, helped me all the time. 我曾经写过的这段代码一直在帮助我。

 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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM