using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WIDESEA_Comm.DataHandle { public class DataParse { /// /// 字节转bit字符串(注意偏移量0,对应的是下标0) /// /// 字节 /// public static char[] Byte2Bit(byte b) { var strTemp = Convert.ToString(b, 2).PadLeft(8, '0').ToCharArray(); Array.Reverse(strTemp); return strTemp; } /// /// 获取字符串【西门子】 /// /// 源 /// 起始位置 /// public static string GetStr(byte[] socure, int start) { //有效长度 int truelength = socure[start + 1]; //前两位是西门标识位 if (truelength > socure.Length - 2) { truelength = socure.Length - 2; } List newByte = new List(); for (int i = 0; i < truelength; i++) { newByte.Add(socure[start + i + 2]); } return Encoding.ASCII.GetString(newByte.ToArray()).Replace("\0", ""); } /// /// 8比特位转字节 /// /// 第一个权重最低 /// 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; } } }