You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module.UpsEqm.ModBusTcp
{
public class BitsConvertUtils
{
/// <summary>
/// 得到字节中Bit组合的值,高位在前,低位在后(高字节在数组低索引位,低字节在数组高索引位)
/// </summary>
/// <param name="data">字节数组</param>
/// <param name="byteAddr">字节位置:数组中第几个字节(从0开始)</param>
/// <param name="bitStartAddr">Bit在字节中的位置:第几位(从0开始)</param>
/// <param name="bitOffset">字节中位的偏移量</param>
/// <returns>返回字节结果byte:1,0</returns>
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;
}
/// <summary>
/// 字节数组转字符串
/// </summary>
/// <param name="byteDatas"></param>
/// <returns></returns>
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;
}
}
}