Zahra
Zahra

Reputation: 45

Convert decimal integers into 4-bit binary

I want to convert decimal integers taken from an array and convert into 4-bit binary and store each of the bit into array in c#

static void Main()
{
    BinaryInput a = new BinaryInput();
    int[] input = { 7, 0, 0, 0, 2, 0, 4, 4, 0 };
    int x;
    int[] bits = new int[36];
    ArrayList Actor = new ArrayList();
    for (int i = 0; i < input.Length; i++)
    {
        x = (int)input[i];
        string result = Convert.ToString(x, 2);
        bits = result.PadLeft(4, '0').Select(c =>int.Parse(c.ToString())).ToArray();
        Actor.Add(bits);
    }
}

The ArrayList Actor consists of 9 arrays and each array consist of binary number......but i want to add each of the binary bit in a single array as an individual element of the array or arraylist {0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0}

Upvotes: 0

Views: 919

Answers (2)

juharr
juharr

Reputation: 32296

You can write a method to get the "bits" of a number like this

private static IEnumerable<int> ToBitSequence(this int num, int size)
{
    while (size > 0)
    {
        yield return num & 1;
        size--;
        num >>= 1;
    }
}

Then you can use it in the following way to get your desired results.

int[] input = { 7, 0, 0, 0, 2, 0, 4, 4, 0 };
var bits = input.Reverse().SelectMany(i => i.ToBitSequence(4)).Reverse();
Console.WriteLine(string.Join(",", bits));

Results in

0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0

The reason for the two Reverse calls is because ToBitSequence will return the least significant bit first, so by feeding the number in reverse order and then reversing the results you will get the bits from most significant to least starting with the first number in your list.

This is preferable to all the parsing and formatting between char, string, and int that you're currently doing.

However if you just change Actor to List<int> and do Actor.AddRange(bits); that would also work.

Upvotes: 3

Kyle W
Kyle W

Reputation: 3752

Use BitArray

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

This will give you the bits, then use

bits.Take(4).Reverse()

to get the least significant 4 bits in most-significant order first for each number.

Upvotes: 0

Related Questions