# C++ Binary Numbers

• Apr 16th 2013, 02:11 PM
sakonpure6
C++ Binary Numbers
I wrote a
Quote:

program that outputs the binary number of a decimal number passed to it, however the binary number out putted has an extra 0 in the 10s place

Code:

```#include <iostream> #include <cmath> using namespace std; void hi (int x) {     double counter=2;     double i=1;     double binary;     double number=0;     while(x!=0)     {     binary=((x%2)*i);        number=number+binary;     i=pow(10,counter);     counter++;         x=x/2;     }     cout<<number; } int main () {     int x;     cout<<"Enter number: ";     cin>>x;     hi(x);     return 0; }```

Nvm I got it :) here is the code if any one is interested, it's pretty simple!
Code:

```#include <iostream>#include <cmath> using namespace std; void hi (int x) {         double counter=0;         double i=1;         double binary;         double number=0;         do         {                 i=pow(10,counter);                 counter++;         binary=((x%2)*i);         x=x/2;     number=number+binary;                         }         while(x!=0);         cout<<number<<endl; } int main () {         int x;         cout<<"Enter number: ";         cin>>x;         hi(x);         return 0; }```
• Apr 16th 2013, 03:06 PM
emakarov
Re: C++ Binary Numbers
If you care to read, I have a couple of remarks. It is a little strange to use a double (or an int, for that matter) as an intermediate result, i.e., to have a variable number that, when written in decimal, equals the original variable x written in binary. I would use a string (an array of characters or Booleans) instead where I would record binary digits of x as I compute them.

Even if your intermediate result is a number, it is generally a bad idea to use types double and float for things that are integer by nature. It is better to declare all local variables of hi() to be int or long int and instead of using pow(), which returns a real number, multiply i by 10 in each iteration: this way you stay inside integers.
• Apr 16th 2013, 03:25 PM
sakonpure6
Re: C++ Binary Numbers
I am only beginner and I don't have the vast knowledge, so I don't know how to deal with strings or Boolean types, and I the only reason I used double is so i can do pow! Thank you for your insight, much appreciated.