Changing integer to binary string of digits(将整数更改为二进制数字字符串)
问题描述
我目前正在用 C++ 模拟 MIPS 处理器,用于一个 comp 架构类,并且在从十进制数转换为二进制数(双向有符号数)时遇到了一些问题.直到最后一点,一切都运行良好,因为我当前的算法在 1<<=31 上属于 int 的边界区域.只需要朝正确的方向轻推即可启动并运行.谢谢!
I'm currently working on a simulation of the MIPS processor in C++ for a comp architecture class and having some problems converting from decimal numbers to binary (signed numbers both ways). Everything's working fine until the very last bit because my current algorithm falls into out of bounds areas for int on 1<<=31. Just need a nudge in the right direction to get it up and running. Thanks!
//Assume 32 bit decimal number
string DecimalToBinaryString(int a)
{
string binary = "";
int mask = 1;
for(int i = 0; i < 31; i++)
{
if((mask&a) >= 1)
binary = "1"+binary;
else
binary = "0"+binary;
mask<<=1;
}
cout<<binary<<endl;
return binary;
}
为了完整性,我还包括了我的其他算法.对于没有发表评论,我深表歉意,但这是相当直截了当的.
I'm also including my other algorithm for completeness. I apologize for the lack of comments, but it's fairly straight forward.
int BinaryStringToDecimal(string a)
{
int num = 0;
bool neg = false;
if(a.at(0) == '1')
{
neg = true;
for(int x = a.length()-1; x >= 0; x--)
{
if(a.at(x) == '1')
a.at(x) = '0';
else a.at(x) = '1';
}
a.at(a.length()-1) += 1;
for(int x = a.length()-1; x >= 0; x--)
{
if(a.at(x) == '2')
{
if(x-1 >= 0)
{
if(a.at(x-1) == '1')
a.at(x-1) = '2';
if(a.at(x-1) == '0')
a.at(x-1) = '1';
a.at(x) = '0';
}
}
else if(a.at(x) == '3')
{
if(x-1 >= 0)
a.at(x-1) += '2';
a.at(x) = '1';
}
}
if(a.at(0) == '2')
a.at(0) = '0';
else if(a.at(0) == '3')
a.at(0) = '1';
}
for(int x = a.length()-1; x >= 0; x--)
{
if(a.at(x) == '1')
num += pow(2.0, a.length()-x-1);
}
if(neg)
num = num*-1;
return num;
}
另外,如果有人知道更有效地编写这些内容的任何好方法,我很想听听.我只上过两门编程入门课程,但一直在尝试不同的技术,看看我有多喜欢他们的风格.
Also if anyone knows any good ways to go about writing these more efficiently I'd love to hear it. I've only had the two introductory programming classes but have been playing with different techniques to see how well I like their style.
推荐答案
实际上有这些标准的单行代码.
There are actually standard one-liners for these.
#include <bitset>
std::string s = std::bitset< 64 >( 12345 ).to_string(); // string conversion
std::cout << std::bitset< 64 >( 54321 ) << ' '; // direct output
std::bitset< 64 > input;
std::cin >> input;
unsigned long ul = input.to_ulong();
将此运行视为演示.
这篇关于将整数更改为二进制数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将整数更改为二进制数字字符串
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
