mirror of
https://gitlab.com/fabinfra/fabaccess/nfc.git
synced 2025-03-12 23:01:45 +01:00
52 lines
1.5 KiB
C#
52 lines
1.5 KiB
C#
|
using System;
|
|||
|
|
|||
|
namespace NFC.Helper
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// Converts to and from Byte Array from and to String
|
|||
|
/// </summary>
|
|||
|
public static class HexConverter
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// Converts byte[] to string with HEX Code
|
|||
|
/// No 0x is created
|
|||
|
/// </summary>
|
|||
|
/// <param name="data">Data</param>
|
|||
|
public static string ConvertToHexString(byte[] data)
|
|||
|
{
|
|||
|
return BitConverter.ToString(data).Replace("-", "").ToLower();
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// Converts string with HEX Code to byte[]
|
|||
|
/// No 0x is requiered
|
|||
|
/// </summary>
|
|||
|
/// <param name="data">Data</param>
|
|||
|
public static byte[] ConvertFromHexString(string data)
|
|||
|
{
|
|||
|
if (data.Length % 2 == 1)
|
|||
|
throw new Exception("Data Length is uneven.");
|
|||
|
|
|||
|
byte[] arr = new byte[data.Length >> 1];
|
|||
|
|
|||
|
for (int i = 0; i < data.Length >> 1; ++i)
|
|||
|
{
|
|||
|
arr[i] = (byte)((GetHexVal(data[i << 1]) << 4) + (GetHexVal(data[(i << 1) + 1])));
|
|||
|
}
|
|||
|
|
|||
|
return arr;
|
|||
|
}
|
|||
|
|
|||
|
private static int GetHexVal(char hex)
|
|||
|
{
|
|||
|
int val = (int)hex;
|
|||
|
//For uppercase A-F letters:
|
|||
|
//return val - (val < 58 ? 48 : 55);
|
|||
|
//For lowercase a-f letters:
|
|||
|
//return val - (val < 58 ? 48 : 87);
|
|||
|
//Or the two combined, but a bit slower:
|
|||
|
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
|
|||
|
}
|
|||
|
}
|
|||
|
}
|