using System;
using System.Collections.Generic;
using System.Text;
namespace Curtain.Net.Sockets.PLC
{
///
/// 转换工具类
///
public static class ConvertTool
{
#region Siemens S7
///
/// 16进制字符转byte[]
///
///
///
///
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 bbs = new List();
while (i < hex.Length)
{
bbs.Add(Convert.ToByte(hex.Substring(i, length), 16));
i += length;
}
return bbs.ToArray();
}
///
/// byte[]转16进制字符
///
///
///
///
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();
}
///
/// byte转16进制字符
///
///
///
///
public static string ByteToHexStr(byte item, int length = 2)
{
return Convert.ToString(item, 16).ToUpper().PadLeft(length, '0');
}
///
/// bool[]转byte[]
/// 8个bool合成一个byte
/// Siemens S7
///
///
///
public static byte[] BoolsToBytes(bool[] data)
{
if (data == null)
{
return null;
}
List bytes = new List();
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();
}
///
/// byte[]转bool[]
/// 一个byte拆成8个bool
/// Siemens S7
///
///
///
///
public static bool[] BytesToBools(byte[] data, int length)
{
if (data == null)
{
return null;
}
List bools = new List();
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
}
}