Click here to Skip to main content
15,888,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have write two methods to convert Hex string to ASCII and ASCII string to Hex string. But when I compare the two strings it I getting two difference Hex strings.

Eg:
Hex string = 6220000008a01000

I convert this string to ASCII using below method

C#
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
C#
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

Can anyone help me to figure it out what happen in there.
Posted

1 solution

Try this:

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

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

    return sb.ToString();
}
 
Share this answer
 
v2
Comments
Soft009 19-Mar-15 5:31am    
I need solution for Hex string to ASCII conversion method

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900