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? – kabibe sadagat 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

4 Answers4

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
  • 54,920
  • 13
  • 119
  • 171
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
  • 1,851
  • 4
  • 19
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.

Solved Games
  • 1,361
  • 3
  • 16
0

I just want to add... if you are curious there are different ways to display the binary representation of a number, here are some of the methods I know.

  1. using std::bitset - the stl library will do the job.
  2. using shifts - here we get each bits of the given number using shifts, I suggest learning how left and right shifts work.
  3. using the division method - the method you mostly learn in school and what you are probably trying to do, here we divide the number by 2 and get the remainder, at this point the remainder can only be 1 or 0 and those remainder is our binary, we also set the vale of num with the quotient of the floor division for each iteration.

NOTE:

  • when working directly with bits you should be wary about the endianness of your system, the bit size of your variable, and your number being unsigned or not.
#include <iostream>
#include <bitset>

#define BITS_OF_INT sizeof(int)*8

int main(){
    int num = 788;

    // using bitset
    std::cout << "std:bitset\n";
    std::bitset<BITS_OF_INT> binary(num);
    std::cout << binary << "\n";
    std::cout << binary.to_string() << "\n";

    // using shifts
    std::cout << "\n\nusing shifts\n";
    for(size_t i=0; i<(BITS_OF_INT); ++i){
        unsigned int bit = num;
        bit <<= i;
        bit = bit >> ((BITS_OF_INT)-1);
        std::cout << bit; // you can convert this to a string or char then add to another string
    }
    std::cout << "\n\n";

    // using division and remainder = (mod = %)
    // this only works for positive values
    std::cout << "using division\n";
    int temp = num;
    std::string binary_str;
    for(size_t i=0; i<BITS_OF_INT; ++i){
        int remainder = temp % 2;
        temp /= 2;
        binary_str.insert(binary_str.begin(),'0'+remainder);
    }
    std::cout << binary_str << "\n";

    return 0;
}
kabibe sadagat
  • 307
  • 1
  • 11