I'm having some trouble with how to implement this correctly. I'd like any clues or insight on this please.
currently I'm doing a crappy temp workaround:
if(Globals.BitsOut1.Value == 32)
{
Globals.txLed6.Value = 1;
}
else
{
Globals.txLed6.Value = 0;
}
I have a (uint32) decimal value coming in from a program where Globals are being given to me by a serial cable from a micro controller,so for example 32.
Now I need to convert that decimal value to an 8 bit "array" of sorts that shows each bit separately. For example,
//LED7,LED6,LED5,LED4,LED3,LED2,LED1//
decimal 1 -> 0,0,0,0,0,0,0,1 which means LED 1 of 7 is on rest are off
decimal 2 -> 0,0,0,0,0,0,1,0 which means LED 2 of 7 is on rest are off
decimal 3 -> 0,0,0,0,0,0,1,1 which means LED 1 and 2 of 7 is on rest are off
decimal 4 -> 0,0,0,0,0,1,0,0 which means LED 3 of 7 is on rest are off
... etc
decimal 32-> 0,0,1,0,0,0,0,0 which means LED 6 of 7 is on rest are off
Now I'm interested how to implement reading ALL these possible values efficiently instead of picking out just the "relevant" LEDS because if I get say for example decimal 33 from the micro controller, the respective LEDS won't turn on right?
Any help would be greatly appreciated!
Answer:
From: Convert int to a bit array in .NET
int value = Globals.BitsOut1.Value;
BitArray b = new BitArray(new int[] { value });
bool[] bits = new bool[b.Count];
b.CopyTo(bits, 0);
byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray();
Globals.txLed1.Value = (int)bitValues[0];
Globals.txLed2.Value = (int)bitValues[1];
Globals.txLed3.Value = (int)bitValues[2];
Globals.txLed4.Value = (int)bitValues[3];
Globals.txLed5.Value = (int)bitValues[4];
Globals.txLed6.Value = (int)bitValues[5];
Globals.txLed7.Value = (int)bitValues[6];