简体   繁体   English

十六进制字符串到ASCII的转换以及ASCII到十六进制的转换问题

[英]Hex string to ASCII conversion and ASCII to Hex conversion issue

I have write two methods to convert Hex string to ASCII and ASCII string to Hex string. 我编写了两种方法来将十六进制字符串转换为ASCII和将ASCII字符串转换为十六进制字符串。 But when I compare the two strings it I getting two difference Hex strings. 但是,当我比较两个字符串时,会得到两个不同的十六进制字符串。

Eg: Hex string = 6220000008a01000 例如:十六进制字符串= 6220000008a01000

I convert this string to ASCII using below method 我使用以下方法将此字符串转换为ASCII

public static string ConvertHex(string hexString)
{
    try
    {
        string ascii = string.Empty;

        for (int i = 0; i < hexString.Length; i += 2)
        {
            string hs = string.Empty;

            hs = hexString.Substring(i, 2);
            ulong decval = Convert.ToUInt64(hs, 16);
            long deccc = Convert.ToInt64(hs, 16);
            char character = Convert.ToChar(deccc);
            ascii += character;

        }

        return ascii;
    }
    catch (Exception ex) { Console.WriteLine(ex.Message); }

    return string.Empty;
}

and I convert that ASCII value back to hex string using below method 然后使用以下方法将该ASCII值转换回十六进制字符串

public string ASCIItoHex(string Value)
{
    StringBuilder sb = new StringBuilder();

    byte[] inputByte = Encoding.UTF8.GetBytes(Value);

    foreach (byte b in inputByte)
    {
        sb.Append(string.Format("{0:x2}", b));
    }

    return sb.ToString();
}

But as the final hex string I get below string. 但是作为最后的十六进制字符串,我得到的是字符串以下的字符串。

Hex string = 6220000008c2a01000 十六进制字符串= 6220000008c2a01000

Can anyone help me to figure it out what happen in there? 谁能帮我弄清楚那里发生了什么?

You try to represent two characters of a hex string (like "FF") as a single char . 您尝试将十六进制字符串的两个字符(例如“ FF”)表示为单个char That does not work. 那行不通。

Your "hexString" is already the string representation of your hex number. 您的“ hexString”已经是您的十六进制数字的字符串表示形式。

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

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