using System; using System.Linq; using System.Text; namespace Xylem.Common.CommonCore.CommonMeasurementUnits { public static class BitExtensions { public static Byte[] GetBits(this Byte[] bytes) { if (bytes is null) { return Array.Empty(); } var bytesCount = bytes.Length; var bitsCount = bytesCount * 8; var bits = new Byte[bitsCount]; var bit = 0; foreach (var @byte in bytes) { for (Int32 b = 7; b >= 0; b--) { bits[bit++] = (Byte)((@byte >> b) % 2); } } return bits; } public static Byte[] GetBytes(this Byte value, Int32 take = 1) => Enumerable.Take(BitConverter.GetBytes(value), take); public static Byte[] GetBytes(this SByte value, Int32 take = 2) => Enumerable.Take(BitConverter.GetBytes(value), take); public static Byte[] GetBytes(this Int16 value, Int32 take = 2) => Enumerable.Take(BitConverter.GetBytes(value), 2); public static Byte[] GetBytes(this UInt16 value, Int32 take = 2) => Enumerable.Take(BitConverter.GetBytes(value), 2); public static Byte[] GetBytes(this Int32 value, Int32 take = 4) => Enumerable.Take(BitConverter.GetBytes(value), take); public static Byte[] GetBytes(this UInt32 value, Int32 take = 4) => Enumerable.Take(BitConverter.GetBytes(value), take); public static Byte[] GetBytes(this Int64 value, Int32 take = 8) => Enumerable.Take(BitConverter.GetBytes(value), take); public static Byte[] GetBytes(this UInt64 value, Int32 take = 8) => Enumerable.Take(BitConverter.GetBytes(value), 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(); } var length = bytes.Length; var swapped = new Byte[length]; for (Int32 x = 0; x < length; x++) { swapped[x] = bytes[length - x - 1]; } return swapped; } public static Byte[] Take(this Byte[] bytesSRC, Int32 count) { if (bytesSRC is null || count < 0) { return Array.Empty(); } 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(); } return value .Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries) .Select(x => byte.TryParse(x, out Byte b) ? b : default(Byte)) .ToArray(); } } }