Convert Strings to Hexadecimal in C#
Hexadecimal, often referred to as hex, is a base-16 numbering system widely used in computing. In this article, we will walk you through a simple program that shows how to convert strings to their hexadecimal representation in C#.
using System;
using System.Text;
class Program
{
static void Main()
{
// Input string
string inputString = "Hello, Techies!";
// Convert string to hexadecimal
string hexResult = StringToHex(inputString);
// Display results
Console.WriteLine($"Input String: {inputString}");
Console.WriteLine($"Hexadecimal Result: {hexResult}");
Console.ReadKey();
}
static string StringToHex(string input)
{
// Convert string to byte array
byte[] byteArray = Encoding.UTF8.GetBytes(input);
// Convert byte array to hexadecimal string
StringBuilder hexBuilder = new StringBuilder();
foreach (byte b in byteArray)
{
hexBuilder.Append(b.ToString("X2")); // X2 ensures two-digit representation
}
return hexBuilder.ToString();
}
}
Output:
Input String: Hello, Techies!
Hexadecimal Result: 48656C6C6F2C205465636869657321
Comments (0)