Reputation: 45
I have a function that convert a Byte to an 8 bit address and returns the bit on the location that is specified in the parameter.
The way it's build now it works fine, but it's pretty ugly in my opinion is there a way to do this with a method in math or something in that direction, I tried looking for another approach but didn't came up with anything.
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();
}
Thanks in advance.
Upvotes: 3
Views: 2928
Reputation: 11216
Another option that might be suitable is to use 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]}");
Output:
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
Upvotes: 0
Reputation: 45135
Use a bitmask.
private bool ConvertByteToBitAddres(byte byteToConvert, int bitToReturn)
{
int mask = 1 << bitToReturn;
return (byteToConvert & mask) == mask;
}
Upvotes: 4
Reputation: 1062600
Use bitwise operations; for example:
int mask = 1 << (bitToReturn - 1); // if "bitToReturn" is 1-based
// int mask = 1 << bitToReturn; // if "bitToReturn" is 0-based
return (byteToConvert & mask) != 0
Perhaps easier, though, is to just pass in the mask
rather than bitToReturn
.
Upvotes: 3