Divide single Value for a many in table C#

98 views Asked by At

From

int BinaryTable = new int[] { 1101 };

To

int BinaryTable = new int[] { 1,1,0,1 };

Don't know how to change it right.

3

There are 3 answers

0
Dmitry Bychenko On

Quick and dirty LINQ:

 int value = 1101; // a bit strange representation 

 int[] BinaryTable = value
   .ToString()
   .Select(c => c - '0')
   .ToArray();

Or since 13 == 1101 binary:

  int value = 13; // just an integer

  int[] BinaryTable = Convert.ToString(value, 2)
    .Select(c => c - '0')
    .ToArray();

In case you want convert one array into another array, use SelectMany instead of Select:

  int[] source = new int[] {1101};

  int[] BinaryTable = source
    .SelectMany(value => value.ToString()
      .Select(c => c - '0')) 
    .ToArray();

Or int[] source = new int[] {13};

  int[] BinaryTable = source
    .SelectMany(value => Convert
       .ToString(value, 2)
       .Select(c => c - '0')) 
    .ToArray();
0
Maksim Simkin On

You could do it this way:

var bits = BinaryTable.Select(b => 
                 b.ToString().
                 Select(r => r == '0'  ? 0 : 1))
              .SelectMany(x => x);

This works if you want to get from

[1101,11] → [1,1,0,1,1,1]

. It is not really clear what exact do you want. And this solution doesn't check that your input really contains only 1 and 0 digits, since it is integer it could theoretically contain every number.

0
CodingYoshi On
int[] BinaryTable = new int[] { 1101 };
List<int[]> allItems = new List<int[]>();
foreach (var item in BinaryTable)
{
    var items = item.ToString().Select(y => int.Parse(y.ToString())).ToArray();
    allItems.Add(items);
}

var final = allItems.SelectMany(x => x).ToArray();