0

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];
  • you would use bit masks do check for the status of single bits. look into the documentation of the binary and operator (&), or for a bit less boolean arithmetic, use a BitArray. – Cee McSharpface Mar 21 '18 at 19:48
  • https://stackoverflow.com/questions/6758196/convert-int-to-a-bit-array-in-net – Ron Beyer Mar 21 '18 at 19:48
  • https://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32(v=vs.110).aspx – Hans Passant Mar 21 '18 at 19:53
  • 1
    you should not use decimal, long is the correct type, also using an Enum based on long can help to make the code more readable – Gusman Mar 21 '18 at 20:00
  • @RonBeyer omg you're a genius! That got it for me, thanks so much! This was solved by looking at bits coming in, (32). Then making a BitArray class for bits coming in. Transforming it to bool values and then sending whether that (LED) is on or off for each spot in the array. – Mathew Lefebvre Mar 21 '18 at 22:10

0 Answers0