/// <summary>
/// byte数据和int、bit转换类
/// </summary>
public class ByteUtil
{
/// <summary>
/// 从int中取出某一位的byte值
/// </summary>
/// <param name="source">原int数据</param>
/// <param name="position">取值位置[0-4]</param>
/// <returns>position所在位的byte数值</returns>
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;
}
/// <summary>
/// 将byte数组转换成int数值
/// </summary>
/// <param name="source">要转换的byte数组</param>
/// <returns>int数值</returns>
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;
}
/// <summary>
/// 从byte数据中获取某一位bit值
/// </summary>
/// <param name="sourceData">原始byte数据</param>
/// <param name="position">取值位置[0-7]</param>
/// <returns>byte数据在position位置的bit值</returns>
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;
}
/// <summary>
/// 设置byte数据中某一位bit值
/// </summary>
/// <param name="sourceData">原始byte数据</param>
/// <param name="position">bit赋值的位置</param>
/// <param name="flag">赋值数据0或1:true代表赋值为1,false代表赋值为0</param>
/// <returns>赋值之后的byte数据</returns>
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;
}
}
12-01
536