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
VulpesPosted Apr 26, 2011, 4:23 PM
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!
Giwa AbdulhakeemPosted Apr 26, 2011, 4:47 PM
Giwa AbdulhakeemPosted Apr 26, 2011, 11:15 AM
Suthish NairPosted Apr 26, 2011, 10:15 AM
VulpesPosted Apr 25, 2011, 4:16 PM
Giwa AbdulhakeemPosted Apr 25, 2011, 12:21 PM
CrishPosted Mar 28, 2011, 1:22 AM
VulpesPosted Mar 27, 2011, 7:14 AM
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;
}
}
VulpesPosted Mar 27, 2011, 6:34 AM
Giwa AbdulhakeemPosted Mar 27, 2011, 1:16 AM
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
Mahesh ChandPosted Mar 27, 2011, 12:02 AM
http://www.csharphelp.com/2007/09/converting-between-binary-and-decimal-in-c/