4

This is what I have:

string decimal_to_binary(int n){
string result = "";
while(n > 0){
    result = string(1, (char) (n%2 + 48)) + result;
    n = n/2;
}
return result; }

This works, but it doesn't work if I put a negative number, any help?

4
  • Check for negative values of n and take appropriate action. What do you want the function to do with negative values? Commented Jan 31, 2017 at 3:15
  • Please clarify your question.. where do you "put" the negative number in this? If n is negative then while (n > 0) fails to enter and so you return an empty string. Is that what you intended? It would be better to post a MCVE that produces some output, and explain how the output differs from what you wanted. Commented Jan 31, 2017 at 3:15
  • @M.M - Yes, n is my value. I just realized that I had the n > 0. Do I need an if statement to separate negatives from positive ints ? Commented Jan 31, 2017 at 3:18
  • That would be one option, but you still haven't shown what behaviour you want to result for negative n Commented Jan 31, 2017 at 3:19

3 Answers 3

2

Just

#include <bitset>

Then use bitset and to_string to convert from int to string

std::cout << std::bitset<sizeof(n)*8>(n).to_string();

It works for negative numbers too.

Sign up to request clarification or add additional context in comments.

Comments

1

Well I would recommend calling a separate function for negative numbers. Given that, for example, -1 and 255 will both return 11111111. Converting from the positive to the negative would be easiest instead of changing the logic entirely to handle both.

Going from the positive binary to the negative is just running XOR and adding 1.

You can modify your code like this for a quick fix.

string decimal_to_binary(int n){
    if (n<0){ // check if negative and alter the number
        n = 256 + n;
    }
    string result = "";
    while(n > 0){
        result = string(1, (char) (n%2 + 48)) + result;
        n = n/2;
    }
    return result;
}

1 Comment

can you do the same with 32 bit?
0

This works, but it doesn't work if I put a negative number, any help?

Check whether the number is negative. If so, call the function again with -n and return the concatenated result.

You also need to add a clause to check against 0 unless you want to return an empty string when the input is 0.

std::string decimal_to_binary(int n){
   if ( n < 0 )
   {
      return std::string("-") + decimal_to_binary(-n);
   }

   if ( n == 0 )
   {
      return std::string("0");
   }

   std::string result = "";
   while(n > 0){
      result = std::string(1, (char) (n%2 + 48)) + result;
      n = n/2;
   }
   return result;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.