### Decimal to binary

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.

 ``12345678910111213141516`` `````` 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:"<
Hello,
The % symbol, called modulo, gives the remainder of a division. For example, 4%2 = 0
Ok, So say if I am to take the number 5 that is 101 in binary:

rem = 5%2 =1
sum = 0 + (1*1) = 1
dec = 5/2 = 2.5
i = 1*10 = 10

how does the sum = 101 if it equals 1 above?

The values are integers. Thus 5/2 = 2, not 2.5.
`sum` starts with an initial value of 0.
inside the loop, a value is added to sum each time around.
Last edited on
In which case how would it look if you were to work it out like I did in my last reply?
You could try adding some `cout` statements to the code and discover the answers for yourself.
 ``1234567891011121314151617181920212223242526272829303132`` ``````#include #include using namespace 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 `unsigned long long`, but that's just patching up something which is basically unsound.
Last edited on
Thank you Chervil, I never thought on doing this! Also thanks for the note that you left at the bottom, good to know.
Topic archived. No new replies allowed.