using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace WIDESEA_Comm.DataHandle
|
{
|
public class DataParse
|
{
|
/// <summary>
|
/// 字节转bit字符串(注意偏移量0,对应的是下标0)
|
/// </summary>
|
/// <param name="b">字节</param>
|
/// <returns></returns>
|
public static char[] Byte2Bit(byte b)
|
{
|
var strTemp = Convert.ToString(b, 2).PadLeft(8, '0').ToCharArray();
|
Array.Reverse(strTemp);
|
return strTemp;
|
}
|
|
/// <summary>
|
/// 获取字符串【西门子】
|
/// </summary>
|
/// <param name="socure">源</param>
|
/// <param name="start">起始位置</param>
|
/// <returns></returns>
|
public static string GetStr(byte[] socure, int start)
|
{
|
//有效长度
|
int truelength = socure[start + 1];
|
//前两位是西门标识位
|
if (truelength > socure.Length - 2)
|
{
|
truelength = socure.Length - 2;
|
}
|
List<byte> newByte = new List<byte>();
|
for (int i = 0; i < truelength; i++)
|
{
|
newByte.Add(socure[start + i + 2]);
|
}
|
return Encoding.ASCII.GetString(newByte.ToArray()).Replace("\0", "");
|
}
|
|
/// <summary>
|
/// 8比特位转字节
|
/// </summary>
|
/// <param name="bitStr">第一个权重最低</param>
|
/// <returns></returns>
|
public static byte Bit2Byte(char[] chardatas)
|
{
|
if (chardatas.Length != 8)
|
{
|
throw new Exception("请输入8位的bit字符串");
|
}
|
|
int res = 0;
|
for (int i = 0; i < 8; i++)
|
{
|
var value = short.Parse(chardatas[i].ToString()) * Math.Pow(2, i);
|
res += (int)value;
|
}
|
if (res > 255)
|
{
|
throw new Exception("bit超出字节大小255");
|
}
|
return (byte)res;
|
}
|
}
|
}
|