using System; using System.Collections.Generic; using System.IO; using System.Linq; 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) { return BitConverter.ToInt16(bytes.ToArray()); } public static int ReadInt(this Stream bytes) { var buffer = new byte[2]; bytes.Read(buffer); return BitConverter.ToInt16(buffer); } public static string ReadIntString(this Stream bytes, int length) { var buffer = new byte[length]; bytes.Read(buffer); return string.Concat(buffer.Select(o => o.ToString())); } public static string ReadASIIString(this Stream bytes, int length) { var buffer = new byte[length]; bytes.Read(buffer); return new string(buffer.Select(o => (char)o).ToArray()); } public static string ReadHexString(this Stream bytes, int length) { var buffer = new byte[length]; bytes.Read(buffer); return BitConverter.ToString(buffer).Replace("-", "").ToLower(); } public static string ReadHexStringDesc(this Stream bytes, int length) { var buffer = new byte[length]; bytes.Read(buffer); return BitConverter.ToString(buffer.Reverse().ToArray()).Replace("-", "").ToLower(); } public static byte[] Read(this Stream bytes, int length) { var buffer = new byte[length]; bytes.Read(buffer); return buffer; } } }