convert a number from base 10 to base 2 in csharp

To convert a number from base 10 (decimal) to base 2 (binary) in C#, you can use the Convert.ToString method with a second parameter of 2 to specify the base.

Here's an example function that takes a decimal number as input and returns its binary equivalent:

main.cs
public static string DecimalToBinary(int num)
{
    return Convert.ToString(num, 2);
}
87 chars
5 lines

You can call this function on any decimal number, like this:

main.cs
int decimalNum = 42;
string binaryNum = DecimalToBinary(decimalNum);
Console.WriteLine(binaryNum); // Output: 101010
117 chars
4 lines

In this example, decimalNum is the input decimal number and binaryNum is the binary equivalent returned by the DecimalToBinary function. The Console.WriteLine statement outputs the binary number to the console.

gistlibby LogSnag