Decimal value for binary in C ++
Well, I would recommend calling a separate function for negative numbers. Given that, for example, -1 and 255 will return 11111111. Converting from positive to negative will be easiest, rather than completely changing the logic to handle both.
Switching from positive binary to negative is just starting XOR and adding 1.
You can change 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;
}
It works, but it does not work if I put a negative number, any help?
Check if the number is negative. If so, call the function again with -nand return the concatenated result.
You also need to add a sentence to check for 0 if you don't want to return an empty string when 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;
}