DECIMAL to BINARY conversion

I am trying to convert a decimal number to a binary number through the following code, but its returning junk values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include<iostream.h>
#include<conio.h>
void main()
{ int n;
 int k=9;
 char str[10];
 cout<<"Enter the no. whose binary equivalent you wan to calculate.";
 cin>>n;

 while(n>1)
 { str[k--]=n%2;
  n=n/2;
  }
  cout<<"\n\t The binary equivalent is "<<str;

  getch();
}


What is wrong with this code? Can anyone please point out the error. Thanks in advance!
This is a problem str[k--]=n%2; because str is a char[] and n is an integer. I'm surprised ur not getting compile errors...
There are no compile errors.
when ever I try with static allocation like
char str[2]=56;
and when i print that statement, it gives correct output of 56. Then i wonder whats wrong?
1, "char" actually is "integer" when talking about the storage way in one byte space. So it's why there is no error in #12, but #12 is one implicit type casting from "integer" to "char", since neither interger '0' and '1' stands for one actual char character, so the type casting always didn't work, a default value was given. "junk values' means it's some rubbish in the memory, not actual the values.

2, #15, "str" is an pointer to a char array. Printing like these means "cout" will print everything out starting from str[0] until meeting '\0'. How about if str[0] is '\0' at the beginning;

3, to change the code more C++ looking. You can try to use "ostringstream" or "string" to store the binary values. You can use string to store all characters, and then print the string out by using iterator. Check "string" reference to get some hints. :)
and also, if you use void main() and <iostream.h> it's just not realy c++, or some realy old dialect. If your compiler doesn't war you about those 2 errors, you should throw it away.
You hould use vectors and push the values in the normal order into the vector. Later you just reverse the vector(std::reverse()) to get the real binary equvalent
Here is an implementation I did back in 2001. Like viliml states. Using a vector from the STL container library to store the bin number is a better way to implement this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Routine that converts decimal numbers to binary
// Author: Wayne Wheeler
// Date: 4/20/2001

#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;

int main ()
{
    vector <int> bin_vector;
    long bin_num, dividend;

      cout << "Enter the decimal number you want converted to binary: ";
      cin >> dividend;


      while ( dividend >= 1 )
        {
           bin_num = dividend % 2;
           dividend /= 2;
           bin_vector.push_back(bin_num);
        }

      cout << endl << endl << endl;
      cout << "The binary equivelant is -->  ";
      for ( int i = (int) bin_vector.size() - 1; i >= 0; i-- )
           cout << bin_vector[i] << "";
    getch();
    return 0;
}
closed account (zb0S216C)
1
2
3
4
5
6
int Value(1234);
const int BitsPerByte(8);
const int OverallSize(sizeof(Value) * BitsPerByte);

for(int I(0); I < OverallSize; ++I)
    std::cout << ((Value &(1 << I)) ? 1 : 0);

Wazzak
@Framework
Your program produced:
01001011001000000000000000000000
when it should have produced:
10011010010
This function will convert integer shorts:
1
2
3
4
5
6
7
8
9
10
11
12
13
void print_binary(short input_field) {     
    int i = 1,bit_set;                     
                                                  
    printf("in binary this is                  ");
       while (i <=16) {                   
           bit_set=((0x8000 & input_field) > 0);   
                                      
           printf("%hd",bit_set);             
           
           input_field <<=  1;// move 1 bit to the left
           i++;
              
        }


closed account (zb0S216C)
buffbill wrote:
"when it should have produced:
10011010010"

My code does exactly what it's supposed to: Print the state of every bit within an int. I don't even know what your code is even doing. Mine is more efficient, though.

Wazzak
Last edited on
Everyone seems to have missed the actual problems.

The first is that 0 and 1 are not the same as '0' and '1'.

The second is your loop condition. (You are stopping at n = 1. You might want to reconsider that.)

The third is some confusion between arrays and strings. The simplest way to fix it is to prefill it with spaces:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include<iostream.h>
#include<conio.h>
void main()
{ int n;
 int k=9;
 char str[] = "          ";  // (k+1) spaces, and an automatic '\0' at the end
 cout<<"Enter the no. whose binary equivalent you wan to calculate.";
 cin>>n;

 while(n>1)
 { str[k--]=(n%2) + '0';  // remember, 0 and '0' are two different values!
  n=n/2;
  }
  cout<<"\n\t The binary equivalent is "<<str;

  getch();
}

BTW, I recommend you not put statements on the same line as your opening braces {. It'll make it much more readable and maintainable for you.

Read more about array strings here:
http://cplusplus.com/faq/sequences/strings/c-strings-and-pointers/

Good luck!
Topic archived. No new replies allowed.