Reputation: 76
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?
Upvotes: 4
Views: 4600
Reputation: 575
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;
}
Upvotes: 1
Reputation: 206607
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;
}
Upvotes: 0
Reputation: 471
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.
Upvotes: 2