4

Possible Duplicate:
Decimal to binary conversion in c #

I have number such as 3, 432, 1, etc . Where I need to convert these number to set of zero & ones, and then store these bits in an array of integers, but not sure how I can get the bits representation of any integer.

Community
  • 1
  • 1
John John
  • 1
  • 72
  • 238
  • 501
  • 10
    Please put "c# integer to binary" to google. And the first link will be (surprise-surprise) http://stackoverflow.com/questions/2954962/decimal-to-binary-conversion-in-c PS: always consult to google before trying to do that with humans - don't think your issue is unique. – zerkms Oct 19 '12 at 09:37
  • ...which is not quite what he's asing – Rawling Oct 19 '12 at 09:38
  • 1
    `"but not sure how I can get the bits representation of any integer."` which is answered in the duplicate. – phant0m Oct 19 '12 at 09:39
  • @Rawling: using the same magic tool (the google) you can change the question to "c# integer to array of bytes" and get (surprise-surprise) another question http://stackoverflow.com/questions/1318933/c-sharp-int-to-byte But indeed, for some people using such a difficult tool like google is a rocket science – zerkms Oct 19 '12 at 09:40
  • There we go, then :p Edit: no wait, that's a byte per byte, not an int per bit. – Rawling Oct 19 '12 at 09:40
  • @zerkms Bits aren't bytes though :P – phant0m Oct 19 '12 at 09:41
  • @phant0m: agree. But I won't put the 3rd google query here (it's not even funny anymore). But there is an answer for bits there as well. – zerkms Oct 19 '12 at 09:42
  • 2
    @zerkms Now who'd have thought you could find [that](http://stackoverflow.com/questions/6758196/convert-int-to-a-bit-array-in-net) on Google. – phant0m Oct 19 '12 at 09:43

2 Answers2

19

Use Convert.ToString Method (Int32, Int32)

Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.

int val = 10;
string binaryNumberString = Convert.ToString(val, 2);

To put them in an int array try:

int[] arr = new int[binaryNumberString.Length];
int i=0;
foreach (var ch in binaryNumberString)
{
    arr[i++] = Convert.ToInt32(ch.ToString());
}
Habib
  • 219,104
  • 29
  • 407
  • 436
6

You can use the Convert.ToString() method

int n = 50;
int b = 2;

string binaryForm = Convert.ToString(n, b);
Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33
Vinod Vishwanath
  • 5,821
  • 2
  • 26
  • 40