using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module.UpsEqm.ModBusTcp
{
public class BitsConvertUtils
{
///
/// 得到字节中Bit组合的值,高位在前,低位在后(高字节在数组低索引位,低字节在数组高索引位)
///
/// 字节数组
/// 字节位置:数组中第几个字节(从0开始)
/// Bit在字节中的位置:第几位(从0开始)
/// 字节中位的偏移量
/// 返回字节结果,byte:1,0
public static byte ByteToBitsValue(byte[] data, int byteAddr, int bitStartAddr, int bitOffset)
{
byte result = 9;
if (data.Count() >= (byteAddr + 1))
{
byte value = data[byteAddr];
if ((bitStartAddr + bitOffset) <= 8)
{
byte temp = 0;
for (int i = bitStartAddr; i < bitStartAddr + bitOffset; i++)
{
temp += (byte)(((value >> i & 1)) << (i - bitStartAddr));
}
result = temp;
}
}
return result;
}
///
/// 字节数组转字符串
///
///
///
public static string BytesTostr(byte[] byteDatas)
{
string strResult = "";
for (int i = 0; i < byteDatas.Length; i++)
{
try
{
strResult += Convert.ToChar(byteDatas[i]).ToString() + Convert.ToChar(byteDatas[i + 1]).ToString();
i++;
}
catch (Exception e)
{
e.ToString();
}
}
return strResult;
}
}
}