0

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

4
Contributors
8
Replies
9
Views
5 Years
Discussion Span
Last Post by ddanbe
2

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 by skatamatic: n/a

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

0

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

Edited by varunme: n/a

1
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();
        }
    }
}
0
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

1

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 by ddanbe: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.