How can we convert an 8bit binary to an array and find the index of high(1 s) in that binary ?

Let me know if this Linq needs any clarification:

//To generate the bool array
bool[] myBits = (from bit in Convert.ToString(myByte, 2).PadLeft(8, '0') 
                             select bit == '1')
                             .ToArray<bool>();
//To display
myBits.ToList().ForEach(y => Console.Write(y ? "1" : "0"));

Edited 4 Years Ago by skatamatic: n/a

how can i get the index of the 1s in the array ?

Byte myByte ;
            myByte = 0X0A;
            //To generate the bool array
            bool[] myBits = (from bit in Convert.ToString(myByte, 2).PadLeft(8, '0')
                             select bit == '1')
                                         .ToArray<bool>();
            //To display
            myBits.ToList().ForEach(y => Console.Write(y ? "1" : "0"));

same way you would in any array:

bool GetBitAtIndexZero = myBits[0];

Note that the result is a boolean value (true or false). If you want this to be an integer (1 or 0) you will need to convert it.

Not nesscary to convert to int,
just to get the index of zeros or ones

Edited 4 Years Ago by varunme: n/a

using System;
using System.Collections.Generic;

namespace Testing {
    class Program {
        static void Main(string[] args) {
            int a = 11111111;

            List<int> index = new List<int>();
            int pos = 0;
            while (a > 0) {
                if ((a & 1) == 1) {
                    index.Add(pos);
                }
                a /= 2;
                pos++;
            }

            foreach (int i in index) {
                Console.WriteLine("{0}", i);
            }


            Console.ReadLine();
        }
    }
}
using System;
using System.Collections.Generic;

namespace Testing {
    class Program {
        static void Main(string[] args) {
            int a = 11111111;

            List<int> index = new List<int>();
            int pos = 0;
            while (a > 0) {
                if ((a & 1) == 1) {
                    index.Add(pos);
                }
                a /= 2;
                pos++;
            }

            foreach (int i in index) {
                Console.WriteLine("{0}", i);
            }


            Console.ReadLine();
        }
    }
}

its giving output but 12 values,
and index is not the correct

The output of 12 is correct if you take into account that 11111111(decimal) is 101010011000101011000111 in binary.
The index list will contain all the indexes of the ones in the number a.

Edited 4 Years Ago by ddanbe: n/a

This article has been dead for over six months. Start a new discussion instead.