Good day,
I want to convert decimal to binary number using c# asp.net. I know there is a certain 'CONVERT' method i could to achieve this, but is that i want the result with details.
For example: decimal to binary (10 to base2)
10 / 2 = 5 R 0
5 / 2 = 2 R 1
2 / 2 = 1 R 0
1 / 2 = 0 R 1
So the corresponding result to 10 = 1010 in base 2. So therefore, if a user type in 10 he gets 1010 and how the result was came about. please help ... :) .. Thanks in advance.
Loading

VulpesRank #55 · 29.2K reputationPosted Apr 26, 2011, 12:23 PM EDT
As requested in your e-mail, I've extended the program to cover the 4 additional conversions.
Your RadioButtonList1 should now have the following 6 options:
1. Binary to Decimal
2. Decimal to Binary
3. Hex to Decimal
4. Decimal to Hex
5. Hex to Binary
6. Binary to Hex
The last 2 don't do much as you can convert between the two just by replacing 4 binary digits with the corresponding hex digit or vice versa - no calculations are necessary.
I've altered all the routines to use 'long' rather than 'int' arithmetic so that bigger numbers can be catered for. However, there's no overflow checking so don't make them too big!
Mahesh ChandRank #1 · 393.3K reputationPosted Mar 26, 2011, 8:02 PM EDT
http://www.csharphelp.com/2007/09/converting-between-binary-and-decimal-in-c/
Giwa Abdulhakeem25 reputationPosted Mar 26, 2011, 9:16 PM EDT
Thanks for the quick response really appreciate it. From the link you posted i tried the section which say Decimal to Binary and i get this error 'Index was outside the bounds of the array.' Tried debugging but all to no result. Would really appreciate any help. Cheers
VulpesRank #55 · 29.2K reputationPosted Mar 27, 2011, 2:34 AM EDT
VulpesRank #55 · 29.2K reputationPosted Mar 27, 2011, 3:14 AM EDT
using System;
class Test
{
static void Main()
{
string bin = "1010";
int dec = BinToDec(bin);
Console.WriteLine("{0} in decimal is {1}", bin, dec);
Console.ReadKey();
}
static int BinToDec (string bin)
{
if (String.IsNullOrEmpty(bin))
throw new ArgumentException("Binary number must contain at least one digit");
int total = 0;
int pow2 = 1;
for (int i = bin.Length - 1; i >= 0; i--)
{
char digit = bin[i];
if (digit != '0' && digit != '1')
throw new ArgumentException("Binary number can only contain 0 or 1");
int product = (digit - 48) * pow2;
total += product;
Console.WriteLine("{0} x {1} = {2} T {3}", digit, pow2, product, total);
pow2 *= 2;
}
return total;
}
}
CrishRank #1,487 · 1.1K reputationPosted Mar 27, 2011, 9:22 PM EDT
Giwa Abdulhakeem25 reputationPosted Apr 25, 2011, 8:21 AM EDT
VulpesRank #55 · 29.2K reputationPosted Apr 25, 2011, 12:16 PM EDT
Suthish NairRank #92 · 22.8K reputationPosted Apr 26, 2011, 6:15 AM EDT
Giwa Abdulhakeem25 reputationPosted Apr 26, 2011, 7:15 AM EDT
Giwa Abdulhakeem25 reputationPosted Apr 26, 2011, 12:47 PM EDT