using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Infrastructure.Extensions { public static class ByteExtensions { public static string ToBitString(this byte @byte) { return Convert.ToString(@byte, 2).PadLeft(8, '0'); } public static int ToInt(this IEnumerable bytes) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } return BitConverter.ToInt16(bytes.ToArray()); } public static int ReadInt(this Stream bytes) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[2]; bytes.Read(buffer); return BitConverter.ToInt16(buffer); } public static string ReadIntString(this Stream bytes, int length) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[length]; bytes.Read(buffer); return string.Concat(buffer.Select(o => o.ToString(CultureInfo.CurrentCulture))); } public static string ReadASIIString(this Stream bytes, int length) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[length]; bytes.Read(buffer); return Encoding.ASCII.GetString(buffer).Trim('\0'); } public static string ReadHexString(this Stream bytes, int length) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[length]; bytes.Read(buffer); return BitConverter.ToString(buffer.Reverse().ToArray()).Replace("-", ""); } public static string ReadHexStringDesc(this Stream bytes, int length) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[length]; bytes.Read(buffer); return BitConverter.ToString(buffer.Reverse().ToArray()).Replace("-", "", StringComparison.CurrentCulture).ToLower(CultureInfo.CurrentCulture); } public static byte[] Read(this Stream bytes, int length) { if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } var buffer = new byte[length]; bytes.Read(buffer); return buffer; } } }