Khalil Kaddoura
Khalil Kaddoura

Reputation: 15

Converting a decimal number to binary in c++

this code finds the binary of a decimal integer N; it divides the number by 2 and takes the floor of the result and divides it also by 2,
the code gets the remainder of those divisions 0 or 1 and builds up the binary.

The problem with this code is that it won't run until the last division example (take 128 the last division is 1/2 and remainder is 1, the program stops at N/2 > 0 as specified in the while loop and 1/2 = 0 since 1 is of type int).

How do I resolve this issue or how do I modify the condition in the while loop?

#include <iostream>
using namespace std;
void ConvertToBinary(int N);
int main()
{
    int N = 1;
    while (1)
    {
        cout << "enter N: ";
        cin >> N;
        cout << endl;
        ConvertToBinary(N);
        cout << endl;
    }
    system("pause");
    return 0;
}
void ConvertToBinary(int N)
{
    int A[1000];
    int i=0;
    cout << "The binary of " << N << "= ";
    while (N / 2 > 0)
    {
        if (N % 2 == 0)
        {
            A[i] = 0;
        }
        else if (N % 2 != 0)
        {
            A[i] = 1;
        }
        N = N / 2;
        i++;
    }
    for (int j= i-1 ; j>=0 ; j--)
    {
        cout<<A[j];
    }


    cout << endl;

}

Upvotes: 0

Views: 1432

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

N is not "a decimal integer". It is a number.

If you really want to talk specifics, it's already stored in binary.

What you're talking about is representation. What is the representation of the number when printed to screen? IOStreams by default will show you numbers in decimal.

You can use I/O Manipulators, though, to choose hexadecimal or octal instead. Sadly there isn't a std::bin yet, but we can use std::bitset for the same purpose:

#include <iostream>
#include <iomanip>
#include <bitset>

int main()
{
    int x = 42;
    std::cout << x << '\n';
    std::cout << std::hex << x << '\n';
    std::cout << std::oct << x << '\n';
    std::cout << std::bitset<sizeof(x)>(x) << '\n';
}

// Output:
//   42
//   2a
//   52
//   1010

(live demo)

And your whole approach (to "fake" a representation shift by changing your number to another number that happens to look like the binary representation of the original number when you print it in decimal representation — phew!) becomes obsolete, solving your problem effortlessly.

Upvotes: 2

Related Questions