0

I was asked to write code for converting a decimal to its binary form. I have tried several different ways but doesn't gives me the order i need. So i am currently stuck on how to proceed.

I have tried by normally finding the binary comparison but it gives me in the incorrect order, lets say the correct order is 1001100, i just get 0011001. and i have no way of changing the order. I am not allowed to use any other library other than iostream, cmath and string. I am now trying to simply find the conversion using the exponent 2^exponent.

This is what i currently have:

int num, exp,rem;

string biNum;

cout<<"Enter decimal number: "<<endl;
cin>>num;

for (exp = 0; pow(2, exp) < num; exp++) {
}

while (num > 0) {
    rem = num % (int) pow(2, exp);
    if (rem != 0) {
            biNum = biNum + '1';
    } else {
            biNum = biNum + '0';
    }
    exp--;
    }
cout<<biNum;
return 0;

}

I am currently receiving no result at all.

Knarz
  • 53
  • 1
  • 6
  • 2
    Don't use `pow(2, X)`, as it has a lot of over head. Use left shifting instead: `(1 << X)`. Many processors can implement a left shift in one or two instructions. – Thomas Matthews Aug 07 '19 at 00:24
  • You may want to use bitwise-AND to test for bit positions rather than the remainder operator, `'%'`. Again, an AND operation is usually 1 instruction or a couple more (for loading registers with values). – Thomas Matthews Aug 07 '19 at 00:26
  • 3
    The expected solution to this task will not use `pow()` which is an expensive floating point calculation that has no business being used to do simple integer calculations, that are easily performed using bit-shifting primitives. Not to mention that [floating point math is broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). I can pretty much guarantee you that whoever asked you to write this will reject this kind of a solution. Your C++ book will have more information on the various kinds of bit-shifting operations that are possible in C++. – Sam Varshavchik Aug 07 '19 at 00:26
  • As usual in these questions, the only decimal to binary conversion here is at `cin >> num;`. From there on the number is binary, and this is confirmed by the absence of divisions and remainder operations with the constant 10. What you're really doing is converting from binary to zoned binary. – user207421 Aug 07 '19 at 01:07

3 Answers3

0

Here is an example that collects the bits in Least Significant Bit (LSB):

//...
while (num > 0)
{
  const char bit = '0' + (num & 1);
  biNum += bit;
  num = num >> 1;
}

Explanation

The loop continues until the num variable is zero. There is no point in adding extra zeros unless you really want them.

The (num & 1) expression returns 1 if the bit is 1, or 0 if the bit is 0.
This is then added to the character 0 to produce either '0' or '1'.

The variable is declared as const since it won't be modified after declaration (definition).

The newly created character is appended to the bit string.

Finally, the num is right shifted by one bit (because that bit was already processed).

There are many other ways to collect the bits in Most Significant Bit (MSB) order. Those ways are left for the OP and the reader. :-)

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

Here you go. This outputs the bits in the right order:

#include <iostream>
#include <string>

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

    while (num)
    {
        char bit = (num & 1) + '0';
        biNum.insert (biNum.cbegin (), bit);
        num >>= 1;
    }

    std::cout << biNum;
    return 0;
}

Live demo

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
0

You can use a recursive function to print the result in reverse order, avoiding using a container/array, like so:

void to_binary(int num) {    
    int rem = num % 2;
    num = (num - rem) / 2;    
    if (num < 2){ 
        std::cout << rem << num;
        return;
    }    
    to_binary(num); 
    std::cout << rem;
}

int main()
{
    to_binary(100);
}
seccpur
  • 4,996
  • 2
  • 13
  • 21
  • Isn't that a bit unnecessary here? We shouldn't be using recursion when it can be easily written using iteration. – eesiraed Aug 07 '19 at 02:44