87 lines
2.7 KiB
C#
87 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace CrossProduct.Core
|
|
{
|
|
/// <summary>
|
|
/// the binary encoder class
|
|
/// </summary>
|
|
public class BinaryEncoder
|
|
{
|
|
/// <summary>
|
|
/// Binaries to string.
|
|
/// </summary>
|
|
/// <param name="BinaryConvert">The binary convert.</param>
|
|
/// <returns></returns>
|
|
public static string BinaryToString(byte[] BinaryConvert)
|
|
{
|
|
return BinaryToString(BinaryConvert, BinaryConvert.Length);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Binaries to string.
|
|
/// </summary>
|
|
/// <param name="BinaryConvert">The binary convert.</param>
|
|
/// <param name="lConvertLength">Length of the l convert.</param>
|
|
/// <returns></returns>
|
|
public static string BinaryToString(byte[] BinaryConvert, int lConvertLength)
|
|
{
|
|
if (BinaryConvert == null)
|
|
return "";
|
|
|
|
int nIndex;
|
|
StringBuilder buildString = new StringBuilder(lConvertLength * 2);
|
|
|
|
for (nIndex = 0; nIndex < lConvertLength; nIndex++)
|
|
{
|
|
buildString.AppendFormat("{0:X2}", BinaryConvert[nIndex]);
|
|
}
|
|
|
|
return buildString.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Strings to binary.
|
|
/// </summary>
|
|
/// <param name="BinaryConvert">The binary convert.</param>
|
|
/// <param name="bAssumeString">if set to <c>true</c> [b assume string].</param>
|
|
/// <returns></returns>
|
|
public static byte[] StringToBinary(string BinaryConvert, bool bAssumeString)
|
|
{
|
|
if (BinaryConvert == null || BinaryConvert == "")
|
|
return new byte[0];
|
|
|
|
int nLength = BinaryConvert.Length / 2;
|
|
|
|
if (bAssumeString)
|
|
{
|
|
if (BinaryConvert.Substring(BinaryConvert.Length - 2, 2) == "00")
|
|
nLength--;
|
|
}
|
|
|
|
int nIndex;
|
|
int nPos;
|
|
byte[] ReturnArray = new byte[nLength];
|
|
|
|
for (nPos = 0, nIndex = 0; nPos < nLength; nIndex += 2, nPos++)
|
|
{
|
|
ReturnArray[nPos] = byte.Parse(BinaryConvert.Substring(nIndex, 2), System.Globalization.NumberStyles.HexNumber);
|
|
}
|
|
|
|
return ReturnArray;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Strings to binary.
|
|
/// </summary>
|
|
/// <param name="BinaryConvert">The binary convert.</param>
|
|
/// <returns></returns>
|
|
public static byte[] StringToBinary(string BinaryConvert)
|
|
{
|
|
return StringToBinary(BinaryConvert, true);
|
|
}
|
|
}
|
|
}
|