Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the binary representation of a value [duplicate]

Tags:

c#

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.

like image 885
john Gu Avatar asked Nov 29 '22 16:11

john Gu


2 Answers

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());
}
like image 164
Habib Avatar answered Dec 01 '22 05:12

Habib


You can use the Convert.ToString() method

int n = 50;
int b = 2;

string binaryForm = Convert.ToString(n, b);
like image 41
Vinod Vishwanath Avatar answered Dec 01 '22 06:12

Vinod Vishwanath