Friday, May 18, 2007

Converting from Decimal to binary and back

This project was written in C# to demonstrate how to convert data from Decimal to Binary and from Binary back to Decimal number.

Simple Binary Converter

There are a number of ways to convert Decimal to Binary. Here, I used a small function to basically loop through and use division by 2 to convert the decimal number to binary format. Here's the code for the function:

private static string Dec2Bin(Int64 nDecimal)
Int64 nBinaryDigit;
string sBinaryNumber = "";
while (nDecimal > 0)
nBinaryDigit = nDecimal % 2;
sBinaryNumber = nBinaryDigit + sBinaryNumber;
nDecimal = nDecimal / 2;
return sBinaryNumber;

To convert Binary number back to Decimal, we can use the built-in function called Convert as seen in the code snippet below:

txtToDecimal.Text = Convert.ToInt64(txtFromBinary.Text, 2).ToString();

You can download the C# project sample here.

No comments: