0

I am trying to create the binary representation of a given integer, however, when I try to output the string, binaryNum, at the end of the code, nothing is printed. However, if I run cout within the for loop, it will print out the binary representation as the program adds 0's and 1's (I only want the final output, not the steps along the way).

What am I missing?

#include <string>
#include <iostream>
using namespace std;

int main() {
    int num;
    string binaryNum = "";
    int divisor = 1;

    cin >> num;

    while (num > 0) {
        while (num / divisor > 1) {
            divisor *= 2;
        }
        if (num / divisor == 1) {
            binaryNum.push_back('1');
            num = num - divisor;
            divisor /= 2;
            while (num / divisor < 1) {
                divisor /= 2;
                binaryNum.push_back('0');
            }
        }
    }

    cout << binaryNum << endl;

    return 0;
}

Thanks!

TDeV4
  • 11
  • 2
    if you want to output the binary why not use ```std::bitset``` instead? – 0xdeadbeef Feb 18 '22 at 16:30
  • Do not use `using namespace std;` as a global declaration, it's quite [dangerous](https://stackoverflow.com/a/1452738/17939455). – Darth-CodeX Feb 18 '22 at 16:32
  • What are you giving as input? – Kevin Feb 18 '22 at 16:33
  • Given the frequency of `/ divisor` in this code, are you **certain** `divisor` never becomes `0`? Try to step through what an input of `1` will do, and see if division-by-zero is ever reached. – Drew Dormann Feb 18 '22 at 16:35
  • 3
    I'm having trouble following the logic of this code. Just check if the number is odd or even, and push back the corresponding digit. Divide by 2. Repeat until done. Then reverse the characters. – Pete Becker Feb 18 '22 at 16:37
  • `while (num / divisor < 1) {` if num is 0 this ends up causing UB when divisor becomes 0. I saw this pretty quickly debugging with 16 as the input. – drescherjm Feb 18 '22 at 16:37
  • ***What am I missing?*** I say the biggest thing you are missing is you failed to use your debugger effectively. Meaning you did not step through your code line by line looking at the variables and flow for a few inputs. – drescherjm Feb 18 '22 at 16:42

3 Answers3

3

What am I missing?

You are dividing by zero, causing Undefined Behavior.

Consider when num and divisor are 1.

    while (num / divisor > 1) {
        divisor *= 2;
    }

The code above will not loop. 1 > 1 is not true.

    if (num / divisor == 1) {

Then the above if is entered, because 1 == 1.

        binaryNum.push_back('1');
        num = num - divisor;
        divisor /= 2;
        while (num / divisor < 1) {

Then the above code makes divisor equal to 0.

Your algorithm then divides by zero,

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
1

Use bitset header file of C++11 to ease your workflow. For an example:

#include <bitset>
#include <string>
#include <iostream>
#include <limits>

int main(void)
{
    int my_num = 0;
    std::cout << "Enter a number: ";
    std::cin >> my_num;
    std::bitset<std::numeric_limits<int>::digits> foo(my_num);
    std::cout << my_num << " in binary = " << foo << std::endl;
    return 0;
}

Further Reading:

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
0

You can use bitset to convert decimal to binary as such:

#include <string>
#include <iostream>
#include <bitset>

int main() 
{
    unsigned int num;
    std::cin >> num;

    std::cout << std::bitset<8>{num} << std::endl; // Replace 8 with the number of binary digits you wish to print.

    return 0;
}

But the catch here is that this way, the binary number is limited to 8 digits (in this case). So let's talk about your code.

The problem with your code is that at one point, the divisor's value turns to 0. Now you are then doing the following:

while (num / divisor < 1)

And we all know, division by 0 is not possible. So to fix your error, add the following line after 'divisor /= 0;':

if (divisor == 0) break;

This will break out of the major while loop 'while (num > 0)' if divisor == 0, and then will print binaryNum.

Final code:

#include <string>
#include <iostream>

int main() {
    int num;
    std::string binaryNum = "";
    int divisor = 1;

    std::cin >> num;

    while (num > 0) {
        while (num / divisor > 1) {
            divisor *= 2;
        }
        if (num / divisor == 1) {
            binaryNum.push_back('1');
            num = num - divisor;
            divisor /= 2;

            if (divisor == 0) break;
            while (num / divisor < 1) {
                divisor /= 2;
                binaryNum.push_back('0');
            }
        }
    }

    std::cout << binaryNum << std::endl;

    return 0;
}

Also, consider not using the following line in your code:

using namespace std;

...as it is considered as bed practice.

The Coding Fox
  • 1,488
  • 1
  • 4
  • 18