十进制到二进制 在C++中签名

Decimal to Binary Signed in C++

本文关键字:C++ 二进制 十进制      更新时间:2023-10-16

这是我所拥有的:

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

这有效,但是如果我输入负数就不起作用了,有什么帮助吗?

只是

#include <bitset>

然后使用 bitsetto_string 从 int 转换为字符串

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

它也适用于负数。

好吧,

我建议为负数调用一个单独的函数。例如,鉴于 -1 和 255 都将返回11111111。从正转换为负是最容易的,而不是完全改变逻辑来处理两者。

从正二进制到负二进制只是运行 XOR 并加 1。

您可以像这样修改代码以快速修复。

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;
}

这有效,但是如果我输入负数就不起作用了,有什么帮助吗?

检查数字是否为负数。如果是这样,请使用 -n 再次调用该函数并返回串联的结果。

您还需要添加一个子句来检查 0,除非您希望在输入为 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;
}