You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Extensions/HexExtensions.cs

37 lines
1.0 KiB

using System;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Infrastructure.Extensions
{
public static class HexExtensions
{
public static byte[] HexToBytes(this string value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
return Enumerable.Range(0, value.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(value.Substring(x, 2), 16))
.ToArray();
}
public static string BytesToHex(this byte[] bytes)
{
if (bytes is null)
{
throw new ArgumentNullException(nameof(bytes));
}
var hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
hex.AppendFormat(CultureInfo.InvariantCulture, "{0:x2}", b);
}
return hex.ToString();
}
}
}