avirk avirk - 1 year ago 53
C# Question

Decimal To Binary Conversion

I tried with this code in C# but could not get the desired output and i cudn't find where my mstaking in logic.

int rem,n,num=0;
while(n>0)
{
rem=n%2;
num=(num*10)+rem;
n=n/2;
}
Console.WriteLine(num);


But it doesn't give me the right output please tell me how can i accomplish it.

Output:

6 after conversion it sould be 110 but its 11

Answer Source

You can use method Convert.ToString for that:

string binValue = Convert.ToString(number, 2);

If you nead a leading zeros you can use String PadLeft method:

binValue = binValue.PadLeft(10, '0');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download