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

## All 8 Replies

Hi, varunne, welcome at Daniweb :)
This snippet may give you an idea.

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"));``````

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;``

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

``````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) {
}
a /= 2;
pos++;
}

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

}
}
}``````
``````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) {
}
a /= 2;
pos++;
}

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