Hi guys, i am very interested in programming and like to understand how things work. I have code taken from a website here. What I would like to know is how this is working mathematically because I have tried it on paper and it does not seem to be giving me the correct answer. It is a program that converts decimal numbers into their binary form. Also what does the '%' symbol mean?
Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
long dec,rem,i=1,sum=0;
cout << "Enter the decimal to be converted:";
cin >> dec;
do
{
rem=dec%2;
sum=sum + (i*rem);
dec=dec/2;
i=i*10;
}while(dec>0);
cout<<"The binary of the given number is:"<<sum<<endl;
cin.get();
cin.get();
_getche();
return 0;
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
long dec = 5;
long rem;
long i = 1;
long sum = 0;
do
{
rem = dec%2;
cout << " dec: " << dec
<< " sum: " << sum
<< " rem: " << rem
<< " i: " << i
<< " i*rem = " << i*rem << endl;
sum = sum + (i*rem);
dec = dec/2;
i = i*10;
} while (dec>0);
cout << "The binary of the given number is:" << sum << endl;
cin.get();
return 0;
}
Output:
dec: 5 sum: 0 rem: 1 i: 1 i*rem = 1
dec: 2 sum: 1 rem: 0 i: 10 i*rem = 0
dec: 1 sum: 1 rem: 1 i: 100 i*rem = 100
The binary of the given number is:101
Note: this code should have a warning attached to it. It will only work for small values of dec as overflow soon starts to occur with larger values. There are better methods, which can use some of the ideas here, but store the result as a character string rather than as another number.
You can squeeze a bit more use out of this code by declaring i and sum to be type unsignedlonglong, but that's just patching up something which is basically unsound.