Mohanapriya R Mohanapriya R
Updated date Jun 05, 2024
In this article, we will discuss the Hex Decoding in C#. Learn how to convert strings into hexadecimal representations and decode them back.

Converting Strings to Hex Decode in C#:

The below C# program converts it to its hexadecimal representation, and then decodes it back to its original form:

using System;
using System.Text;

class HexDecoder
{
    static void Main()
    {
        // Input string
        string originalString = "Hello, TechieHook.com!";

        // Convert string to hex
        string hexRepresentation = StringToHex(originalString);
        Console.WriteLine($"Original String: {originalString}");
        Console.WriteLine($"Hex Representation: {hexRepresentation}");

        // Decode hex back to string
        string decodedString = HexToString(hexRepresentation);
        Console.WriteLine($"Decoded String: {decodedString}");
    }

    static string StringToHex(string input)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(input);
        return BitConverter.ToString(bytes).Replace("-", "");
    }

    static string HexToString(string hex)
    {
        byte[] bytes = new byte[hex.Length / 2];
        for (int i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return Encoding.UTF8.GetString(bytes);
    }
}

Output:

Original String: Hello, TechieHook.com!
Hex Representation: 48656C6C6F2C20546563686965486F6F6B2E636F6D21
Decoded String: Hello, TechieHook.com!

Comments (0)

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