How to Convert Hex Decoded Strings to Normal Strings in C#?
Hexadecimal encoding is a way of representing binary data in a human-readable format. Each byte of data is represented by two hexadecimal characters. For example, the ASCII character 'A' is represented by the hex value '41'. To convert a hex-encoded string back to its normal representation, we need to decode each pair of hex characters into their corresponding ASCII characters.
C# program that performs the conversion:
using System;
using System.Text;
class HexDecoder
{
static void Main()
{
string hexEncodedString = "48656C6C6F2C20576F726C64"; // Hex-encoded string to be decoded
string decodedString = HexToString(hexEncodedString);
Console.WriteLine("Hex Encoded String: " + hexEncodedString);
Console.WriteLine("Decoded String: " + decodedString);
}
static string HexToString(string hex)
{
StringBuilder stringBuilder = new StringBuilder(hex.Length / 2);
for (int i = 0; i < hex.Length; i += 2)
{
string hexPair = hex.Substring(i, 2);
byte byteValue = byte.Parse(hexPair, System.Globalization.NumberStyles.HexNumber);
stringBuilder.Append((char)byteValue);
}
return stringBuilder.ToString();
}
}
Output:
Hex Encoded String: 48656C6C6F2C20576F726C64
Decoded String: Hello, World
- The
HexDecoder
class contains aMain
method where a hex-encoded string is defined. - The
HexToString
method takes a hex-encoded string as input and iterates through pairs of hex characters, converting them to bytes and then to characters. - The decoded string is printed to the console along with the original hex-encoded string.
Comments (0)