| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Curtain.Net.Sockets.PLC
- {
- /// <summary>
- /// 转换工具类
- /// </summary>
- public static class ConvertTool
- {
- #region Siemens S7
- /// <summary>
- /// 16进制字符转byte[]
- /// </summary>
- /// <param name="hex"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static byte[] HexStrToBytes(string hex, int length = 2)
- {
- if (string.IsNullOrWhiteSpace(hex))
- {
- return null;
- }
- if (hex.IndexOf(' ') > 0)
- {
- hex = hex.Replace(" ", "");
- }
- int i = 0;
- List<byte> bbs = new List<byte>();
- while (i < hex.Length)
- {
- bbs.Add(Convert.ToByte(hex.Substring(i, length), 16));
- i += length;
- }
- return bbs.ToArray();
- }
- /// <summary>
- /// byte[]转16进制字符
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static string BytesToHexStr(byte[] bytes, int length = 2)
- {
- if (bytes == null || bytes.Length == 0)
- {
- return null;
- }
- StringBuilder sb = new StringBuilder();
- foreach (byte item in bytes)
- {
- sb.Append(ByteToHexStr(item, length));
- }
- return sb.ToString();
- }
- /// <summary>
- /// byte转16进制字符
- /// </summary>
- /// <param name="item"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static string ByteToHexStr(byte item, int length = 2)
- {
- return Convert.ToString(item, 16).ToUpper().PadLeft(length, '0');
- }
- /// <summary>
- /// bool[]转byte[]
- /// 8个bool合成一个byte
- /// Siemens S7
- /// </summary>
- /// <param name="data"></param>
- /// <returns></returns>
- public static byte[] BoolsToBytes(bool[] data)
- {
- if (data == null)
- {
- return null;
- }
- List<byte> bytes = new List<byte>();
- for (int i = 0; i < data.Length; i += 8)
- {
- byte item = 0;
- for (int j = 0; j < 8 && i+j< data.Length; j++)
- {
- if (data[i + j])
- {
- item += (byte)Math.Pow(2, j);
- }
- }
- bytes.Add(item);
- }
- return bytes.ToArray();
- }
- /// <summary>
- /// byte[]转bool[]
- /// 一个byte拆成8个bool
- /// Siemens S7
- /// </summary>
- /// <param name="data"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static bool[] BytesToBools(byte[] data, int length)
- {
- if (data == null)
- {
- return null;
- }
- List<bool> bools = new List<bool>();
- foreach (byte item in data)
- {
- char[] cs = Convert.ToString(item, 2).ToCharArray();
- Array.Reverse(cs);
- int count = Math.Min(8, length);
- length -= 8;
- bool[] bs = new bool[count];
- for (int i = 0; i < count && i< cs.Length; i++)
- {
- bs[i] = (cs[i] == '1');
- }
- bools.AddRange(bs);
- }
- return bools.ToArray();
- }
- #endregion
- }
- }
|