我有一个将字节转换为8位地址的函数,并返回参数中指定位置的位。
它的构建方式现在运行正常,但在我看来它是非常丑陋的,有一种方法可以用数学方法或那个方向做一些事情,我试着找另一个方法,但没有想出任何东西。
private bool ConvertByteToBitAddres(byte byteToConvert, int bitToReturn)
{
bool[] address = new bool[8];
int remaining = byteToConvert;
if (remaining > 128)
{
remaining = remaining - remaining;
address[7] = true;
}
if (remaining > 64 || remaining < 128)
{
remaining = remaining - remaining;
address[6] = true;
}
if (remaining > 32)
{
remaining = remaining - remaining;
address[5] = true;
}
if (remaining > 16)
{
remaining = remaining - remaining;
address[4] = true;
}
if (remaining > 8)
{
remaining = remaining - remaining;
address[3] = true;
}
if (remaining > 4)
{
remaining = remaining - remaining;
address[2] = true;
}
if (remaining > 2)
{
remaining = remaining - remaining;
address[1] = true;
}
if (remaining > 1)
{
remaining = remaining - remaining;
address[0] = true;
}
if (remaining == 0)
{
return address[bitToReturn];
}
throw new Exception();
}
提前致谢。
答案 0 :(得分:4)
使用位掩码。
private bool ConvertByteToBitAddres(byte byteToConvert, int bitToReturn)
{
int mask = 1 << bitToReturn;
return (byteToConvert & mask) == mask;
}
答案 1 :(得分:3)
使用按位运算;例如:
int mask = 1 << (bitToReturn - 1); // if "bitToReturn" is 1-based
// int mask = 1 << bitToReturn; // if "bitToReturn" is 0-based
return (byteToConvert & mask) != 0
或许更容易传递mask
而不是bitToReturn
。
答案 2 :(得分:0)
另一个可能适用的选项是使用BitVector32:
byte b = 10;
var bv = new BitVector32(b);
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"Value of bit {i}: {bv[1 << i]}");
}
//You could also declare consts for each bit and use that:
const int Bit0 = 1;
const int Bit1 = 2;
const int Bit2 = 4;
const int Bit3 = 8;
Console.WriteLine($"\r\nValue of bit 3: {bv[Bit3]}");
输出:
Value of bit 0: False
Value of bit 1: True
Value of bit 2: False
Value of bit 3: True
Value of bit 4: False
Value of bit 5: False
Value of bit 6: False
Value of bit 7: False
Value of bit 3: True