[C#]获取与设置Byte中的Bit值
关键知识点:1Byte=8Bit;Bit为二进制;一.获取Byte里的指定Bit值的函数:/// <summary>/// 获取字节中的指定Bit的值/// </summary>/// <param name="this">字节</param>/// <param name="index">Bit的索引值(0-7)</param&g
·
关键知识点:
- 1Byte=8Bit;
- Bit为二进制;
一.获取Byte里的指定Bit值的函数:
/// <summary>
/// 获取字节中的指定Bit的值
/// </summary>
/// <param name="this">字节</param>
/// <param name="index">Bit的索引值(0-7)</param>
/// <returns></returns>
public static int GetBit(this byte @this, short index)
{
byte x = 1;
switch (index)
{
case 0: { x = 0x01; } break;
case 1: { x = 0x02; } break;
case 2: { x = 0x04; } break;
case 3: { x = 0x08; } break;
case 4: { x = 0x10; } break;
case 5: { x = 0x20; } break;
case 6: { x = 0x40; } break;
case 7: { x = 0x80; } break;
default: { return 0; }
}
return (@this & x) == x ? 1 : 0;
}
二.设置Byte里的指定Bit值的函数:
/// <summary>
/// 设置字节中的指定Bit的值
/// </summary>
/// <param name="this">字节</param>
/// <param name="index">Bit的索引值(0-7)</param>
/// <param name="bitvalue">Bit值(0,1)</param>
/// <returns></returns>
public static byte SetBit(this byte @this, short index, int bitvalue)
{
var _byte = @this;
if (bitvalue == 1)
{
switch (index)
{
case 0: { return _byte |= 0x01; }
case 1: { return _byte |= 0x02; }
case 2: { return _byte |= 0x04; }
case 3: { return _byte |= 0x08; }
case 4: { return _byte |= 0x10; }
case 5: { return _byte |= 0x20; }
case 6: { return _byte |= 0x40; }
case 7: { return _byte |= 0x80; }
default: { return _byte; }
}
}
else
{
switch (index)
{
case 0: { return _byte &= 0xFE; }
case 1: { return _byte &= 0xFD; }
case 2: { return _byte &= 0xFB; }
case 3: { return _byte &= 0xF7; }
case 4: { return _byte &= 0xEF; }
case 5: { return _byte &= 0xDF; }
case 6: { return _byte &= 0xBF; }
case 7: { return _byte &= 0x7F; }
default: { return _byte; }
}
}
}
更多推荐


所有评论(0)