You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.8 KiB
99 lines
2.8 KiB
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<byte> 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;
|
|
}
|
|
}
|
|
} |