# c++ print binary number



## DustyMcAwesome (Dec 17, 2008)

Ok, so I'm working on converting a number from decimal to binary, pretty simple.


```
while( i != 0) {
   j = i / 2;
   k = i % 2;
   i = j;
 
   cout << k << endl;
}
```
but the number is print backwards. So 32 is printed 000001.

Any ideas of how I can print this correctly, but still use the math to calculate the binary equivalent?


----------



## AlbertMC2 (Jul 15, 2010)

Hi

You can always store k in an array of integer.
Then when outputting (Is that a word?) it to the screen just reverse the array.

```
int main(int argc, char *argv[])
{
   int i, j, k;
   int arr[10]; 
   
   i = 32;
   k = 0;
   
   while( i != 0) 
   {
       j = i / 2;
       arr[k] = i % 2;
       i = j;
       k++;
    }
    k--;
    while(k>=0)
    {
              cout<<arr[k];
              k--;
    }
    system("PAUSE");
    return 0;
}
```
OR

after a bit of searching there is already a function to do this called BITSET:

```
#include <iostream>
[B]#include <bitset>[/B]

using namespace std;

int main(int argc, char *argv[])
{
   int i;
   
   i = 32;
   
   std::cout << std::bitset<CHAR_BIT>( i ) << std::endl;
   
   system("PAUSE");
   return 0;
}
```


----------



## DustyMcAwesome (Dec 17, 2008)

AlbertMC2 said:


> Hi
> 
> You can always store k in an array of integer.
> Then when outputting (Is that a word?) it to the screen just reverse the array.
> ...


The array solution worked great! The next issued I'm having is reading in the values that need to be converted. The program should read in a string, store the ascii values, and then convert those ascii values as a sort of encryption.
I can convert the string to the correct ascii values, but how could I store them into an array in order to convert them to binary? heres some code;


```
void ConvertToAscii(int a, string str) {
                for(a = 0; a != str.length(); ++a)
                cout << int(str[a]) << ", ";
                cout << endl;
                cin.get();
}

void AsciiToBinary(int a) {
       int arr[10],
            i,
            j,
            k,
            r,
            d,
            b,
            num;
       while(i != 0) {
            j = i / 2;
            arr[k] = i % 2;
            i = j;

           k++
}
       k--;
       while(k >= 0) {
           cout << arr[k] << endl;
           k--;
}
```
Thats the script for the two functions, appropriately named. When I call to the AsciiToBinary function, I need it to convert the ascii values found in the other function. Any ideas?


----------

