Skip Navigation LinksHome > Blog > 2008 > March > 14 > 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();
}