-4

I want to convert my base 10 number to base 2 and then store parts in an array.

Here are two examples:

my value is 5 so it will be converted to 101 then I have an array like this: {1,0,1}

or my value is 26 so it will be converted to 11010 then I will have an array like this: {0,1,0,1,1}

Thank you in advance for your time and consideration.

Farhad E
  • 1
  • 2
  • Welcome to StackOverflow! What have you tried so far? We'd like to help you when you got stuck in your code, but SO is not a free coding service. – René Vogt Feb 22 '16 at 07:18
  • Search for a DEC to BINARY STRING function. Reverse the output. Add add it to an array. – Kris Feb 22 '16 at 07:19

1 Answers1

1

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();

Source: https://stackoverflow.com/a/6758288/1560697

Community
  • 1
  • 1
NoName
  • 7,940
  • 13
  • 56
  • 108