HexToString and StringToHex

Skip Navigation LinksIrocon > Blog > 2008 > March, 2008 > March 14, 2008 > HexToString and StringToHex

HexToString and StringToHex

At the moment I am researching on how to convert a regular string to HEX and back. You may wonder why? I gues I'll explain later.

EDIT:

I have come up with some basic yet incomplete functions to achieve this:

 public static string HexStringToAsciiString(string chars)
{
    if (!string.IsNullOrEmpty(chars))
    {
        return BytesToAsciiString(HexStringToBytes(chars));
    }
    return string.Empty;
}

public static string AsciiStringToHex(string chars)
{
    if (!string.IsNullOrEmpty(chars))
    {
        return BytesToHexString(AsciiStringToBytes(chars));
    }
    return string.Empty;
}


public static string BytesToAsciiString(byte[] bytes)
{
    ASCIIEncoding enc = new ASCIIEncoding();
    return enc.GetString(bytes);
}

public static string BytesToHexString(byte[] bytes)
{
    StringBuilder hexString = new StringBuilder(bytes.Length * 2);
    int len = bytes.Length - 1;
    for (int counter = 0; counter <= len; counter++)
    {
        hexString.Append(string.Format("{0:X2}", bytes[counter]));
    }
    return hexString.ToString();
}

Last Updated:Thursday, September 02, 2010By:alfero#

Would you like to comment?

Sign in with your OpenID. If you do not know what OpenID is, find out.