# Decimal to binary conversion in C++

Page 1 of 1

## 10 Replies - 32190 Views - Last Post: 15 August 2008 - 11:42 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=60511&amp;s=36633f0803925ccb5b1ff06efad5da2a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 xVo1cOmx

• New D.I.C Head

Reputation: 0
• Posts: 4
• Joined: 21-June 08

# Decimal to binary conversion in C++

Posted 13 August 2008 - 07:10 AM

Hello my assign. is all about converting decimal to binary, octal, etc. and I started coding it in C++. I need a little help, well my problem is the resulting answer is correct but it starts on the left-to-rigth allignment. Let say I input a Number 8, the resulting binary of it is 1000, but in my code it will display 0001.

```#include<iostream.h>
main()
{
int num,x,y;
cout <<"Enter a Number : ";
cin >>num;
x=num;
while(x>0)
{
y=x%2;
cout <<y;
x=x/2;
}
cout <<" is the BINARY of " <<num <<"." <<"\n\n\t\t\t";
return(0);
}

```

Is This A Good Question/Topic? 0

## Replies To: Decimal to binary conversion in C++

### #2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

## Re: Decimal to binary conversion in C++

Posted 13 August 2008 - 07:53 AM

you can either make that recursive or copy your value in string and then reverse it.

There are many snippets available for this look one of it here.

### #3 baavgai

• Dreaming Coder

Reputation: 7160
• Posts: 14,924
• Joined: 16-October 07

## Re: Decimal to binary conversion in C++

Posted 13 August 2008 - 11:44 AM

There are a number of ways to attack this, as mentioned. First, let's rewrite this a little bit.

```#include<iostream>

using namespace std;

void printBinary(int x) {
while(x>0) {
cout << x % 2;
x = x / 2;
}
}

int main() {
int num;
cout <<"Enter a Number : ";
cin >>num;
printBinary(num);
cout <<" is the BINARY of " <<num <<"." <<"\n\n\t\t\t";
return 0;
}

```

So, same program, same problem, only now we've isolated the binary output portion into a funcntion.

Using your same methodology, we can print it the other direction using recursion. That is, we'll figure out a value, then call ourself, then print.

```void printBinary(int x) {
if (x==0) { return; }
printBinary(x / 2);
cout << x % 2;
}

```

Of course, you're always loosing your leading zeros. I like bitwise operations for this sort of thing. Here another, completely different take.

```void printBinary(int x) {
int bits = sizeof(x)*8;
int mask = 1 << (bits-1);
while(bits-->0) {
cout << ((x & mask)==0 ? '0' : '1');
x = x << 1;
}
}

```

Hope this helps.

### #4 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Decimal to binary conversion in C++

Posted 13 August 2008 - 03:09 PM

just a note: ((x & mask)==0 ? '0' : '1') has the save function as !((x & mask) == 0) or ((x & mask) != 0)

tip: never use the conditional operator to convert something to to binary (0 or 1) since that happens naturally in the condition portion of the conditional operator.

### #5 baavgai

• Dreaming Coder

Reputation: 7160
• Posts: 14,924
• Joined: 16-October 07

## Re: Decimal to binary conversion in C++

Posted 13 August 2008 - 04:16 PM

Good tip. For the example, I thought the C++ boolean int thingy would make the code even less clear.

Also, I wasn't 100% sure that !0 would resolve to 1. After all, it really is only required to be non 0.

### #6 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Decimal to binary conversion in C++

Posted 13 August 2008 - 08:08 PM

The results of a binary expression are always 0 or 1 (0 false, 1 true). BUT had you just used (x & mask) (which works as a binary expression) this would not evaluate to 0 or 1, so you do need that == or != operator (which is normally not needed) for example using ((x & mask) ? '1' : '0') works the same as ((x & mask) != 0)

I just always hate it when I use the conditional to convert a condition to a binary value. I have written (condition) ? true : false; more than once, just to find it years later and say "What the hell was I doing!" -- but I suppose it DOES make things explicit. There is something to be said for clarity.

This post has been edited by NickDMax: 13 August 2008 - 08:09 PM

### #7 Iamtheboss

• New D.I.C Head

Reputation: 0
• Posts: 1
• Joined: 24-October 07

## Re: Decimal to binary conversion in C++

Posted 14 August 2008 - 03:09 AM

Try this function, I wrote it some time ago...

```//Needs #include <algorithm.h> and #include <vector> and #include <cmath>
vector<int> ToBinary (int conv)
{

vector<int> bin;

while (conv!=0)
{

if( conv%2 == 0) bin.push_back(0);
else bin.push_back(1);
conv = (int) floor(conv/2);
}

reverse(bin.begin(),bin.end());

return bin;

}

```

This post has been edited by Iamtheboss: 14 August 2008 - 03:11 AM

### #8 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Decimal to binary conversion in C++

Posted 14 August 2008 - 06:51 AM

As long as we are thinking in binary:

(numb % 2) is (numb & 1) I don't know if one is better than the other (I hope that optimization makes them the same) but I do remember that in BASIC is was faster to use & for modulus powers of 2. (num & 7) vs (num % 8)

so for example the above may have been written as:
```#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> ToBinary (int conv)
{
vector<int> bin;
while (conv!=0)
{
bin.push_back(conv & 1);
conv >>= 1; //same as conv /= 2;
}
reverse(bin.begin(),bin.end());
return bin;
}

void displaybit (int i) {
cout << i;
}

void displayBinary(vector<int> bin) {
for_each(bin.begin(), bin.end(), displaybit);
}

int main() {
vector<int> bin = ToBinary(0xF5AA); //1111 0101 1010 1010
displayBinary(bin);
cout << endl;
return 0;
}
```

### #9 xVo1cOmx

• New D.I.C Head

Reputation: 0
• Posts: 4
• Joined: 21-June 08

## Re: Decimal to binary conversion in C++

Posted 15 August 2008 - 08:08 AM

I appreciate your help ppl. but i can't get through your codes, in the way of teaching. Our proff. teach us a different way of coding that we should follow, I know it's funny but its a fact. I would like to know your coding style but my proff. will kick my balls ;] This dec to bin code is just a conversion of our C, we just replace the printf to cout and etc.

Anywy this the outcome of what we've done:

```#include<iostream.h>
main()
{
int a,x,y;
char num[12];
cout <<"Enter a Number : ";
cin >>x;
x=y;
a=0;
while(x!=0)
{
y=x%2;
x=x/2;
num[a]=y;
a++;
}
for(;a>=0;a--)
{
cout << num[a];
}
return(0);
}

```

Please correct the code if errors occur. TY in advance

This post has been edited by xVo1cOmx: 15 August 2008 - 08:12 AM

### #10 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Decimal to binary conversion in C++

Posted 15 August 2008 - 10:09 AM

First off: I don't think anyone else here is taking you class so we can code it anyway we want. It is up to YOU to make it work for your implementation.

Secondly: if that is how your teacher is teaching you then he/she should be fired or retired on the spot as they are teaching you bad habits.

For example the "#include <iostream.h>" has long since been depreciated. It is only available for backwards computability but should not be used in new code.

There was a couple of little glitches in your code which I fixed here:
```//Use the new standard headers!
#include<iostream>

//You must access the std namespace to use members
//You can do it like this (telling the compiler specifically
//  what you are using).
using std::cout;
using std::cin;
using std::endl;
//Or you could just add everything by using:
// using namespace std;

//main() should always be defined as at least int main()
int main()
{
//Indentation helps make your code more readable and clear.
//you should REALLY use better variable names!
int a,x,y;
//integers are at least 16 bits and then you should leave room for a
// terminating zero so at a minimum you need 17... but you can use a
// formula to make sure that you always have it right:
//    sizeof(int) * 8 + 1
// the sizeof operator tells you how many bytes are used in that datatype
// since there are 8 bits per byte you multiply by 8 and then add one
// to hold a terminating 0 (though you don't really use that here)
char num[sizeof(int) * 8 + 1];
cout << "Enter a Number : ";
cin >> x;
a=0;
while(x!=0)
{
y=x%2;
x=x/2;
num[a]=y;
a++;
}
a--; //the a++ advanced a to one past the last char
for(;a>=0;a--)
{
//Have to use a cast to make a char into an number
cout << (int)num[a];
//OR we could have done which would convert the numeric value
// of num[a] into the proper char
//cout << (num[a] + '0')
}
//its always a good idea to flush the stream and put a newline before you
// exit your program.
cout << endl;
return(0);
}
```

The biggest problem was that you needed an "a--;" line.

If your teacher is still telling you to use "#include <iostream.h>" and "main()" then perhaps you should ask why you are coding like its the 1980's and not learning standard C++.

### #11 xVo1cOmx

• New D.I.C Head

Reputation: 0
• Posts: 4
• Joined: 21-June 08

## Re: Decimal to binary conversion in C++

Posted 15 August 2008 - 11:42 PM

You're right Nick but for the sake of my Prof. I dont want to be an Einstein on our class..It's a pain in his ass ;] I'll try to convince him to teach us how to use the new standard headers.