EonaCat.HID/EonaCat.HID/Helpers/ByteHelper.cs

35 lines
1.2 KiB
C#

using System;
using System.Linq;
using System.Text;
namespace EonaCat.HID.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public static class ByteHelper
{
public static string ByteArrayToHexString(byte[] bytes, string separator = "")
{
return BitConverter.ToString(bytes).Replace("-", separator);
}
public static byte[] HexStringToByteArray(string hexString)
{
hexString.Trim();
hexString = hexString.Replace("-", "");
hexString = hexString.Replace(" ", "");
return Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
}
public static string GetFilledBytesString(byte[] bytes)
{
var buffer = Encoding.Unicode.GetString(bytes).ToArray();
int index = Array.IndexOf(buffer, '\0');
return new string(buffer, 0, index >= 0 ? index : buffer.Length);
}
}
}