C# Hex.DecodeHex: Decode Hexadecimal Strings - Tutorial & Code Example
In C#, you can use the `System.Security.Cryptography` namespace to decode a hexadecimal encoded string.
Here's an example of how to use `Hex.DecodeHex` method in C#:
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main(string[] args)
{
string hexString = "48656C6C6F20576F726C64"; // Hexadecimal encoded string
byte[] decodedBytes = DecodeHex(hexString);
string decodedString = Encoding.UTF8.GetString(decodedBytes);
Console.WriteLine(decodedString); // Output: Hello World
}
public static byte[] DecodeHex(string hexString)
{
int numberChars = hexString.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return bytes;
}
}
In this example, the `DecodeHex` method takes a hexadecimal encoded string as input and converts it into a byte array. The byte array is then converted to a string using the `Encoding.UTF8.GetString` method to obtain the original decoded string.
Note: Make sure to include the `System.Security.Cryptography` and `System.Text` namespaces in your code.
原文地址: https://www.cveoy.top/t/topic/pvXF 著作权归作者所有。请勿转载和采集!