Convert int to a bit array in .NET

Use the BitArray class.

int value = 3;
BitArray b = new BitArray(new int[] { value });

If you want to get an array for the bits, you can use the BitArray.CopyTo method with a bool[] array.

bool[] bits = new bool[b.Count];
b.CopyTo(bits, 0);

Note that the bits will be stored from least significant to most significant, so you may wish to use Array.Reverse.

And finally, if you want get 0s and 1s for each bit instead of booleans (I'm using a byte to store each bit; less wasteful than an int):

byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray();

To convert the int 'x'

int x = 3;

One way, by manipulation on the int :

string s = Convert.ToString(x, 2); //Convert to binary in a string

int[] bits= s.PadLeft(8, '0') // Add 0's from left
             .Select(c => int.Parse(c.ToString())) // convert each char to int
             .ToArray(); // Convert IEnumerable from select to Array

Alternatively, by using the BitArray class-

BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();

I would achieve it in a one-liner as shown below:

using System;
using System.Collections;

namespace stackoverflowQuestions
{
    class Program
    {
        static void Main(string[] args)
        {    
            //get bit Array for number 20
            var myBitArray = new BitArray(BitConverter.GetBytes(20));
        }
    }
}

Please note that every element of a BitArray is stored as bool as shown in below snapshot:

enter image description here

So below code works:

if (myBitArray[0] == false)
{
    //this code block will execute
}

but below code doesn't compile at all:

if (myBitArray[0] == 0)
{
    //some code
}

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

Tags:

C#

.Net