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.

8
  • 10
    Please put "c# integer to binary" to google. And the first link will be (surprise-surprise) stackoverflow.com/questions/2954962/… PS: always consult to google before trying to do that with humans - don't think your issue is unique. Commented Oct 19, 2012 at 9:37
  • ...which is not quite what he's asing Commented Oct 19, 2012 at 9:38
  • 1
    "but not sure how I can get the bits representation of any integer." which is answered in the duplicate. Commented Oct 19, 2012 at 9: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 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 Commented Oct 19, 2012 at 9:40
  • 2
    @zerkms Now who'd have thought you could find that on Google. Commented Oct 19, 2012 at 9:43

2 Answers 2

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well, it wasn't right, but now it is! +1
6

You can use the Convert.ToString() method

int n = 50;
int b = 2;

string binaryForm = Convert.ToString(n, b);

4 Comments

thanks for the reply,, but what does base means in this case?
@Vinod base is a keyword in c#
ya i know but how it will affect the returned bit values i mean , say i define the base as 2 what will be different if i define the base as 8
@Nick, My bad. Yes, the variable should be renamed to a non-keyword. int reqBase = 2;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.