using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WCS.Data { public class PlcHelper { /// /// Byte转二进制 /// /// /// public static string ByteToBinary(byte dbItem) { char[] cs = Convert.ToString(dbItem, 2).PadLeft(8, '0').ToCharArray(); Array.Reverse(cs); string res = new string(cs); return res; //return Convert.ToString(dbItem, 2).PadLeft(8,'0'); } /// /// Bytes转二进制 /// public static string BytesToBinary(byte[] dbItems) { string result = string.Empty; foreach (byte item in dbItems) { result = result + ByteToBinary(item); } return result; } private static string ReadAlaramCode(string alarm) { string errorResult = string.Empty; StringBuilder sb = new StringBuilder(); for (int i = 0; i < alarm.Length; i++) { int index = i + 1; if (Convert.ToInt16(alarm.Substring(i, 1)) == 1) { sb.Append(string.Format("{0},", index)); } } if (sb.Length > 0) { errorResult = sb.ToString().TrimEnd(','); } return errorResult; } /// /// 查询报警信息 /// /// /// public static string ReadAlaramCodeByBytes(byte[] dbItems) { if (dbItems == null || dbItems.Count() <= 0) return string.Empty; else return ReadAlaramCode(BytesToBinary(dbItems)); } /// /// Byte转换成二进制并取指定位置数字 /// /// db模块 /// 二进制截取的起始位置 /// public static bool ByteToBool(byte dbItem, int startIndex) { int startPos = 0; switch (startIndex) { case 0: startPos = 7; break; case 1: startPos = 6; break; case 2: startPos = 5; break; case 3: startPos = 4; break; case 4: startPos = 3; break; case 5: startPos = 2; break; case 6: startPos = 1; break; case 7: startPos = 0; break; default: startPos = -1; break; } return Convert.ToString(dbItem, 2)//转换成二进制 .PadLeft(8, '0')//字符串长度为8位,不够左边补零 .Substring(startPos, 1) == "0" ? false : true; } } }