Help with Decimal - Binary conversion ?

Hello.
This is code for testing a function that will be included in a larger program.

I'm trying to take an int from the user, then convert it to the equivalent binary number.

My approach so far is to create a string variable that will hold the binary value. I want my if statements to essentially append my string by either adding a character '1' or '0' onto it.

I've looked for examples online, but I don't know how to interpret them. Below you will likely find a confused interpretation.


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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>

using namespace std;



string dec_to_bin(int num){

   string bin;
   






while(num > 0){

 if( num % 2 == 1){
 
    cout << "Your number is odd" << endl;

    bin& += '1';    // Adds '1' to the resultant binary string

    num = (num -1)/2;
 } 
 else{
 cout << " Number is even" << endl;

 bin& += '0';    // Adds '0' to the resultant binary string

 num = num/2;
 }



}
	


}


int main(){

   int num;
   string ans;

cout << "enter int: " ;

cin >> num;
// validate int
ans = dec_to_bin(num);



return 0;
}



Also, I'm trying to come up with an idea for converting a binary number from the user to an integer using similarly simple operations seen here. If you have any ideas to share, that would also be very appreciated.


Thank you very much in advance.
The easy way is to convert the integer into a hex string, and use a lookup table (16 values). Hex is directly convertible to binary. Same for the reverse. This gives you a printable version (string version) very easily (assuming this is what you want). Basically you need 0 to F in binary in a table of strings, then peel of the hex digit and spit out the binary string. so 0F spits out 00001111 and c++ has several ways you can get the hex string from an int value.

integers are already in binary format. you can use bitwise logic operations to print the bits in a loop.
Using brute force, this looks like:
1
2
3
4
5
6
7
8
9
10
11
12
 int x = 1234;	
	
	for(int b = 2048; b > 0; b/=2)
 {
       if(x-b >= 0)
            {
               cout << 1;
               x -= b;
            } 
           else cout << 0 ;
  } 


there are slicker ways to get it, of course.

reverse whatever you do to take binary and get the integer.
Last edited on
Here are two options - one non-recursive, the other recursive.
Both generalise easily to bases other than 2 if you wanted.
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
#include <iostream>
#include <string>
using namespace std;

const string digits = "01";


string toBinary( unsigned n )                    // with a loop
{
   if ( n == 0 ) return "0";
   string result;
   for ( ; n; n /= 2 ) result = digits[ n % 2 ] + result;
   return result;
}


string toBinary2( unsigned n )                   // recursive
{
   return n < 2 ? digits.substr( n, 1 ) : toBinary2( n / 2 ) + digits[ n % 2 ];
}


int main()
{
   for ( unsigned n = 0; n < 32; n++ ) cout << n << '\t' << toBinary( n ) << '\t' << toBinary2( n ) << '\n';
}

0	0	0
1	1	1
2	10	10
3	11	11
4	100	100
5	101	101
6	110	110
7	111	111
8	1000	1000
9	1001	1001
10	1010	1010
11	1011	1011
12	1100	1100
13	1101	1101
14	1110	1110
15	1111	1111
16	10000	10000
17	10001	10001
18	10010	10010
19	10011	10011
20	10100	10100
21	10101	10101
22	10110	10110
23	10111	10111
24	11000	11000
25	11001	11001
26	11010	11010
27	11011	11011
28	11100	11100
29	11101	11101
30	11110	11110
31	11111	11111
This is probably a little more efficient because it creates only one string object. The trick is to build it up backwards and then reverse it at the end.
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
#include <iostream>
#include <string>
#include <algorithm>

using std::string;
using std::reverse;

string toBinary(int num)
{
    string result;
    int bit;
    // Built up the result in reverse order
    while (num) {
	bit = num % 2;
	result += '0' + bit;
	num /= 2;
    }
    reverse(result.begin(), result.end()); // reverse the string
    return result;
}



int
main()
{
    int num;
    while (std::cin >> num) {
	std::cout << num << "\t-> " << toBinary(num) << '\n';
    }
}

I prefer the recursive version, but this alternative fixes the string length once only.

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
#include <iostream>
#include <string>
using namespace std;

string toBinary( unsigned n )
{
   unsigned p = 2, ndigits = 1;
   for ( ; p <= n; p <<= 1 ) ndigits++;          // Increase power until 2^p > n
   string result( ndigits, '0' );                // String of correct length
   for ( unsigned i = 0; i < ndigits; i++ )      // Check all lower powers of 2
   {
      p >>= 1;
      if ( n >= p )
      {
         result[i] = '1';
         n -= p;
      }
   }
   return result;
}


int main()
{
   for ( unsigned n = 0; n < 32; n++ ) cout << n << '\t' << toBinary( n ) << '\n';
}


0	0
1	1
2	10
3	11
4	100
5	101
6	110
7	111
8	1000
9	1001
10	1010
11	1011
12	1100
13	1101
14	1110
15	1111
16	10000
17	10001
18	10010
19	10011
20	10100
21	10101
22	10110
23	10111
24	11000
25	11001
26	11010
27	11011
28	11100
29	11101
30	11110
31	11111

Topic archived. No new replies allowed.