Converting Hexadecimal to Byte in C#
- Hexadecimal: Hexadecimal is a base-16 numbering system that uses sixteen distinct symbols, typically the digits 0–9 and the letters A–F, to represent numbers.
- Bytes: In programming, a byte is a unit of digital information that consists of 8 bits.
C# program to convert Hexadecimal to Byte in C#:
using System;
class Program
{
static void Main()
{
// Define a hexadecimal string
string hexString = "1B3D5AC";
// Convert the hexadecimal string to a byte array
byte[] byteArray = StringToByteArray(hexString);
// Output the byte array
Console.WriteLine("Byte Array:");
foreach (byte b in byteArray)
{
Console.Write(b.ToString("X2") + " ");
}
Console.ReadKey();
}
static byte[] StringToByteArray(string hex)
{
int length = hex.Length;
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
}
We will define a hexadecimal string "1A2B3C"
, then will use the StringToByteArray
method to convert the hexadecimal string to a byte array. The StringToByteArray
method iterates over the hexadecimal string, converting pairs of characters into bytes using the Convert.ToByte
method with base 16 (hexadecimal).
Output:
Byte Array:
1A 2B 3C
Comments (0)