37 lines
1.0 KiB
C#
37 lines
1.0 KiB
C#
using System;
|
|
|
|
namespace CSNetwork
|
|
{
|
|
public static class Helper
|
|
{
|
|
public static byte[] HexStringToByteArray(string hex)
|
|
{
|
|
if (hex.Length % 2 == 1)
|
|
throw new ArgumentException("Hex string must have an even number of digits.");
|
|
|
|
int numberChars = hex.Length;
|
|
byte[] bytes = new byte[numberChars / 2];
|
|
for (int i = 0; i < numberChars; i += 2)
|
|
{
|
|
try
|
|
{
|
|
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
|
|
}
|
|
catch (FormatException ex)
|
|
{
|
|
throw new ArgumentException(
|
|
$"Invalid hex character found at position {i}: '{hex.Substring(i, 2)}'",
|
|
ex
|
|
);
|
|
}
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
public static string ByteToHexString(byte[] bytes)
|
|
{
|
|
return BitConverter.ToString(bytes).Replace("-", "");
|
|
}
|
|
}
|
|
}
|