HexToByteArray
Converts a hexadecimal string to a byte array.
- Use
Enumerable.Range()in combination withstring.Lengthto get the indices of the given string in an array. - Use
Enumerable.Where()to get only the even indices in the previous range. - Use
Enumerable.Select()in combination withConvert.ToByte()andstring.Substring()to convert each byte’s hex code to abyte. - Finally, use
Enumerable.ToArray()to return abyte[].
using System.Linq;
public static partial class _30s
{
public static byte[] HexToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}_30s.HexToByteArray("F15936"); // { 241, 89, 54 }