Mohanapriya R Mohanapriya R
Updated date Apr 08, 2024
Learn how to convert strings to hexadecimal format using a simple C# program.
  • 3.9k
  • 0
  • 0

Converting Strings to Hex Encode using C#

Below is a simple C# program that takes a string as input and converts it to its hexadecimal representation:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Input string
        string inputString = "Hello, Hex Encoding in C#";

        // Convert string to byte array
        byte[] byteArray = Encoding.UTF8.GetBytes(inputString);

        // Convert byte array to hexadecimal string
        string hexString = BitConverter.ToString(byteArray).Replace("-", "");

        // Output the result
        Console.WriteLine("Original String: " + inputString);
        Console.WriteLine("Hex Encoded String: " + hexString);
    }
}

Output:

Original String: Hello, Hex Encoding in C#
Hex Encoded String: 48656C6C6F2C2048657820456E636F64696E6720696E204323

In this example, the input string "Hello, Hex Encoding in C#" is converted to its hexadecimal representation.

  • The input string is converted to a byte array using the UTF-8 encoding.
  • The BitConverter.ToString method is then used to convert the byte array to a string of hexadecimal values.
  • The Replace("-", "") is employed to remove the dashes between hexadecimal pairs, resulting in a continuous string of hexadecimal characters.

Comments (0)

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