///
/// byte数据和int、bit转换类
///
public class ByteUtil
{
///
/// 从int中取出某一位的byte值
///
/// 原int数据
/// 取值位置[0-4]
/// position所在位的byte数值
public byte getByteFromInt(int source,int position) {
if (position < 0 || position > 3) throw new ArgumentOutOfRangeException("position范围值超限");
byte result = (byte)((source >> position * 8) & 0xFF);
return result;
}
///
/// 将byte数组转换成int数值
///
/// 要转换的byte数组
/// int数值
public int getIntFromBytes(byte[] source) {
byte[] rSource = new byte[4];
if (source.Length > 4) throw new ArgumentOutOfRangeException("byte数组范围超限");
for (int i = 0; i < source.Length; i++) {
rSource[i] = source[i];
}
int result = source[3] << 24 | source[2] << 16 | source[1] << 8 | source[0];
return result;
}
///
/// 从byte数据中获取某一位bit值
///
/// 原始byte数据
/// 取值位置[0-7]
/// byte数据在position位置的bit值
public int getBitFromByte(byte sourceData,int position) {
int offset = 0x00;
switch (position) {
case 0:
offset = 0x01;
break;
case 1:
offset = 0x02;
break;
case 2:
offset = 0x04;
break;
case 3:
offset = 0x08;
break;
case 4:
offset = 0x10;
break;
case 5:
offset = 0x20;
break;
case 6:
offset = 0x40;
break;
case 7:
offset = 0x80;
break;
default:
throw new ArgumentOutOfRangeException("position范围值超限");
}
int result = ((byte)(sourceData & offset) == 0) ? 0 : 1;
return result;
}
///
/// 设置byte数据中某一位bit值
///
/// 原始byte数据
/// bit赋值的位置
/// 赋值数据0或1:true代表赋值为1,false代表赋值为0
/// 赋值之后的byte数据
public byte setBitToByte(byte sourceData,int position, bool flag) {
int offset = 0x00;
switch (position)
{
case 0:
offset = 0x01;
break;
case 1:
offset = 0x02;
break;
case 2:
offset = 0x04;
break;
case 3:
offset = 0x08;
break;
case 4:
offset = 0x10;
break;
case 5:
offset = 0x20;
break;
case 6:
offset = 0x40;
break;
case 7:
offset = 0x80;
break;
default:
throw new ArgumentOutOfRangeException("position范围值超限");
}
byte result = flag?(byte)(sourceData | offset):(byte)(sourceData & ~offset);
return result;
}
}