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

## Recommended Answers

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

## 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) {
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.