using JinYuan.Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PLC { /// /// /// public class PLCDataTool { /// /// 将字节数组转成16进制字符串 /// /// /// /// public static string Byte2HexString(byte[] hex, int len) { string returnstr = ""; for (int i = 0; i < len; i++) { returnstr += hex[i].ToString("X2"); } return returnstr; } /// /// 把字符串截取成每个元素2个字符的字符串数组 /// /// /// 前置非数据字节数,omron为30,Mitsubishi为11 /// public static string[] Str2StrArray(string src, int notDataCounts) { try { string[] res; src = src.Substring(2 * notDataCounts); res = new string[src.Length / 2]; for (int i = 0; i < src.Length / 2; i++) { res[i] = src.Substring(i * 2, 2); } return res; } catch (Exception exp) { LogHelper.Instance.WriteError(exp.Message); return null; } } /// /// 将条码转换成UInt16数组 /// 没两个字符对应一个UInt16 /// /// /// public static int[] BarcodeTransfer(string barcode) { byte[] bt = Encoding.ASCII.GetBytes(barcode); if (bt.Length % 2 != 0) { bt = bt.Concat(new byte[] { 0 }).ToArray(); } int[] result = new int[bt.Length / 2]; for (int i = 0; i < bt.Length / 2; i++) { result[i] = Convert.ToUInt16(bt[2 * i].ToString("X2") + bt[2 * i + 1].ToString("X2"), 16); } return result; } /// /// 位转字 /// 输入一个长度16的bool数组,返回一个Int16形式的字 /// 高位在左,低位在右 /// /// /// Word public static ushort BitsToWord(bool[] bits) { ushort result = 0; for (int i = 0; i < 16; i++) { if (bits[i]) result |= (ushort)(1 << i); } return result; } /// /// 字转位 /// 输入一个Int16形式的字,返回一个长度16的bool数组 /// /// /// Bits public static bool[] WordToBits(ushort word) { bool[] result = new bool[16]; for (int i = 0; i < 16; i++) { result[i] = ((word >> i) & 1) == 1; } return result; } /// /// 位转字节 /// /// /// public static byte BitsToByte(bool[] bits) { byte result = 0; for (int i = 0; i < 8; i++) { if (bits[i]) result |= (byte)(1 << i); } return result; } /// /// 字节转位 /// /// /// public static bool[] ByteToBits(byte bt) { bool[] result = new bool[8]; for (int i = 0; i < 8; i++) { result[i] = ((bt >> i) & 1) == 1; } return result; } /// /// 把两个uint16的数据合并成一个float /// /// /// /// public static double TwoUInt16ToFloat(ushort High, ushort Low) { int int_32 = (High << 16) | Low; return BitConverter.ToSingle(BitConverter.GetBytes(int_32), 0); } /// /// 把float分隔成两个int16 /// /// /// 低位在前高位在后 public static ushort[] FloatToTwoUInt16(float value) { byte[] bs = BitConverter.GetBytes(value); ushort low = BitConverter.ToUInt16(bs, 0); ushort high = BitConverter.ToUInt16(bs, 2); return new ushort[2] { low, high }; } /// /// 把int分隔成两个int16 /// /// /// 低位在前高位在后 public static ushort[] Int32ToTwoUInt16(int value) { byte[] bs = BitConverter.GetBytes(value); ushort low = BitConverter.ToUInt16(bs, 0); ushort high = BitConverter.ToUInt16(bs, 2); return new ushort[2] { low, high }; } /// /// 把两个Int16的数据合并成一个Int32 /// /// /// /// public static int TwoInt16ToInt32(short High, short Low) { return ((ushort)High << 16) | (ushort)Low; } } }