I'm very new to C# (and C in general for that matter) I'm getting a byte value returned from an external source that represents the states of 8 input pins on the port of an IO device so I get a value of 0-255 representing the binary pattern present on the port.
How can I strip out the individual bits and set them as bool vars, so doing something like this:
if (inputBuffer[1] == 1)
{
IO.Input0 = true;
IO.Input1 = false;
IO.Input2 = false;
IO.Input3 = false;
IO.Input4 = false;
IO.Input5 = false;
IO.Input6 = false;
IO.Input7 = false;
}
I'm probably overexplaining what I'm trying to achieve but thought this gives the best example although highly impractical, how can I better achieve this to set the variables based on a byte value of 0-255.
Use a bitwise-and (&
). Assuming Input0
represents the least significant bit:
IO.Input0 = (inputBuffer & 0x01) == 0x01;
IO.Input1 = (inputBuffer & 0x02) == 0x02;
IO.Input2 = (inputBuffer & 0x04) == 0x04;
IO.Input3 = (inputBuffer & 0x08) == 0x08;
IO.Input4 = (inputBuffer & 0x10) == 0x10;
IO.Input5 = (inputBuffer & 0x20) == 0x20;
IO.Input6 = (inputBuffer & 0x40) == 0x40;
IO.Input7 = (inputBuffer & 0x80) == 0x80;
You can also implement an extension method like the following:
public static bool IsBitSet(this byte b, int bit)
{
if(bit < 0 || bit > 7)
throw new ArgumentOutOfRangeException("bit must be between 0 and 7");
byte bitToCheck = (byte)(0x01 << bit);
return (b & bitToCheck) == bitToCheck;
}
Which you could then call like:
IO.Input4 = inputBuffer.IsBitSet(4);
Use a bitmask and the &
-operator to figure this out
byte b = 100;
if(b&1 == 1) { } //bit 1 is set
if(b&2 == 2) { } //bit 2 is set
if(b&4 == 4) { } //bit 3 is set
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With