十进制到二进制 在C++中签名
Decimal to Binary Signed in C++
这是我所拥有的:
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>
然后使用 bitset 和 to_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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 有根的二进制搜索树.保留与其父级的链接
- 多态二进制函数
- 正在读取二进制文件(is_open)
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为什么二进制搜索在我的测试中不起作用
- 重载==不适用于二进制树
- 正在尝试重载二进制搜索树分配运算符
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 带有数组键C++的二进制映射
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 二进制数之和(使用C样式字符串)
- 如何从dicom文件中读取二进制数据
- 基于编译器选项的编译二进制路径