C#获得多字节任意连续位转换为int的值
下位机常常返回一个或多个字节,每个比特位都有其含义。连续几位表示一个数值的情况经常出现,在此封装一个帮助类,实现获取任意连续位表示数值的值:
public static class BitHelper { //获取字节任意位的值 1 or 0 public static int GetBitByIndex(byte value, int index) { if (index > 7) { throw new Exception(); } return (value & (0x1 << index)) >> index; } //获取指定起点和终点连续位表示的int值, startIndex = 0, endIndex = values.Length * 8 - 1 public static int GetIntFromPart(byte[] values, int startIndex, int endIndex) { int result = 0; for (int i = startIndex; i <= endIndex; i++) { int n = values.Length - (i / 8) - 1; int p = i > 7 ? i % 8 : i; result += GetBitByIndex(values[n], p) << (i - startIndex); } return result; } }BitHelper
其中字节数组 {0xEF, 0x5F} 等价 0xEF5F ,等价 1110 1111 0101 1111 ,从左到右,由高到低。
由于使用int类型,截取位长不应该超过31位。否则可能溢出。