Mohanapriya R Mohanapriya R
Updated date Apr 13, 2024
In this article, we will discover how to convert Hexadecimal Encoded Strings in C#.

How to Convert Hex-Encoded Strings to Normal Strings?

Hexadecimal encoding represents binary data using a base-16 numbering system. Each hexadecimal digit corresponds to four binary digits, making it a convenient way to express binary data in a more compact and readable form. In C#, hex-encoded strings often appear as sequences of characters, with each pair representing a byte of data.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Hex encoded string example
        string hexEncodedString = "48656C6C6F20576F726C64"; 

        // Convert hex to bytes
        byte[] bytes = HexStringToBytes(hexEncodedString);

        // Convert bytes to string
        string normalString = Encoding.UTF8.GetString(bytes);

        // Display the result
        Console.WriteLine("Hex Encoded String: " + hexEncodedString);
        Console.WriteLine("Decoded String: " + normalString);
    }

    static byte[] HexStringToBytes(string hex)
    {
        int length = hex.Length;
        byte[] bytes = new byte[length / 2];

        for (int i = 0; i < length; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }

        return bytes;
    }
}
  • Hex Encoded String: Start with a hex encoded string. In this example, "48656C6C6F20576F726C64" represents the ASCII values for "Hello World."
  • Convert Hex to Bytes: Utilize the HexStringToBytes method to convert the hex encoded string into an array of bytes.
  • Convert Bytes to String: Use Encoding.UTF8.GetString to convert the byte array into a normal string.
  • Display Result: Output both the original hex encoded string and the decoded normal string.

Output:

Hex Encoded String: 48656C6C6F20576F726C64
Decoded String: Hello World

Comments (0)

There are no comments. Be the first to comment!!!