laatzen/Common/CommonMessurementUnits/BitExtensions.cs
2023-08-25 15:23:57 +02:00

118 lines
3.3 KiB
C#

namespace CommonMessurementUnits
{
using System;
using System.Linq;
using System.Text;
public static class BitExtensions
{
public static byte[] GetBits(this byte[] bytes)
{
if (bytes is null)
{
return Array.Empty<byte>();
}
var bytesCount = bytes.Length;
var bitsCount = bytesCount * 8;
var bits = new byte[bitsCount];
var bit = 0;
foreach (var @byte in bytes)
{
for (int b = 7; b >= 0; b--)
{
bits[bit++] = (byte)((@byte >> b) % 2);
}
}
return bits;
}
public static byte[] GetBytes(this byte value, int take = 1)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this sbyte value, int take = 2)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this short value, int take = 2)
=> BitConverter.GetBytes(value).Take(2);
public static byte[] GetBytes(this ushort value, int take = 2)
=> BitConverter.GetBytes(value).Take(2);
public static byte[] GetBytes(this int value, int take = 4)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this uint value, int take = 4)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this long value, int take = 8)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this ulong value, int take = 8)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this double value)
=> BitConverter.GetBytes(value);
public static byte[] GetBytes(this string value)
=> Encoding.ASCII.GetBytes(value);
public static byte[] Swap(this byte[] bytes)
{
if (bytes is null)
{
return Array.Empty<byte>();
}
var length = bytes.Length;
var swapped = new byte[length];
for (int x = 0; x < length; x++)
{
swapped[x] = bytes[length - x - 1];
}
return swapped;
}
public static byte[] Take(this byte[] bytesSRC, int count)
{
if (bytesSRC is null || count < 0)
{
return Array.Empty<byte>();
}
var bytesDST = new byte[count];
Array.Copy(bytesSRC, 0, bytesDST, 0, count);
return bytesDST;
}
public static string ToHex(this byte[] value, string separator = " ")
{
if (value is null)
{
return string.Empty;
}
return BitConverter.ToString(value).Replace("-", separator);
}
public static byte[] FromHex(this string value, string separator = " ")
{
if (string.IsNullOrWhiteSpace(value))
{
return Array.Empty<byte>();
}
return value
.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => byte.TryParse(x, out byte b) ? b : default(byte))
.ToArray();
}
}
}