Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy and fast way to convert an int to binary?

Tags:

c#

What I am looking for is something like PHPs decbin function in C#. That function converts decimals to its representation as a string.

For example, when using decbin(21) it returns 10101 as result.

I found this function which basically does what I want, but maybe there is a better / faster way?

like image 369
Max Avatar asked Dec 03 '09 10:12

Max


People also ask

What are the two methods to convert the decimal number to binary number?

However, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction.


Video Answer


3 Answers

var result = Convert.ToString(number, 2);

– Almost the only use for the (otherwise useless) Convert class.

like image 187
Konrad Rudolph Avatar answered Oct 21 '22 01:10

Konrad Rudolph


Most ways will be better and faster than the function that you found. It's not a very good example on how to do the conversion.

The built in method Convert.ToString(num, base) is an obvious choice, but you can easily write a replacement if you need it to work differently.

This is a simple method where you can specify the length of the binary number:

public static string ToBin(int value, int len) {
   return (len > 1 ? ToBin(value >> 1, len - 1) : null) + "01"[value & 1];
}

It uses recursion, the first part (before the +) calls itself to create the binary representation of the number except for the last digit, and the second part takes care of the last digit.

Example:

Console.WriteLine(ToBin(42, 8));

Output:

00101010
like image 31
Guffa Avatar answered Oct 21 '22 03:10

Guffa


int toBase = 2;
string binary = Convert.ToString(21, toBase); // "10101"
like image 10
Rubens Farias Avatar answered Oct 21 '22 01:10

Rubens Farias