How to convert string to hex in C#

By FoxLearn 11/26/2024 8:22:44 AM   116
To convert a string to its hexadecimal representation in C#, you can use the following method.

In C#, you can convert a string to its hexadecimal representation by encoding the string into bytes and then converting each byte to its hexadecimal form.

Using Encoding.UTF8.GetBytes(input) converts the input string to a byte array.

For example:

string StringToHex(string input)
{
    // Convert the string to bytes using UTF-8 encoding
    byte[] bytes = Encoding.UTF8.GetBytes(input);
    // Build the hexadecimal representation
    StringBuilder sb = new StringBuilder(bytes.Length * 2);
    foreach (byte b in bytes)
        sb.AppendFormat("{0:X2}", b); // Uppercase hex
    return sb.ToString();
}

Use a StringBuilder to efficiently build the hex string, then use b.ToString("X2") formats each byte as a 2-digit uppercase hexadecimal string. Use "x2" for lowercase hex.