Click here to Skip to main content
14,332,489 members
Rate this:
Please Sign up or sign in to vote.
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

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

Rate this:
Please Sign up or sign in to vote.

Solution 1

Try this:

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

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

    return sb.ToString();
}
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100