# Numerical computations in C++ : Converting from Decimal to Binary

April 17, 2011 Leave a comment

Converting from decimal to binary notation is fairly standard and straightforward.

Let’s say we need to find the binary representation of .

The method that most of us would have been taught in school is the following:

– Divide 100 by 2. You get 50, with remainder = 0. Write 0.

– Divide 50 by 2, to get 25 and remainder = 0. Write 0.

– Divide 25 by 2 to get 12 and remainder = 1. Write 1.

– Continue doing so until the number (which is 25 at present) becomes 0.

– The binary representation of 100 is the reverse of what you have written.

——

We can write a recursive function to compute the binary representation of a decimal number. Using the power of recursion, we can avoid having to reverse the output as is necessitated by the above method.

——-

**// Function dec_to_bin outputs the binary equivalent of the decimal number n. **

**void dec_to_bin ( int n) **

**{**

**if ( n < 0) **

**{**

**cout << “-“;**

**n = -n;
**

**}
**

**if (n == 0) **

**return; **

**dec_to_binary (n/2); **

**cout << n%2;
**

**}**

**——–**

dec_to_bin will take time proportional to the number of bits in the binary equivalent of n.

——–