Pau*_*uiz 23 c++ algorithm binary
我目前正在使用C++模拟MIPS处理器,用于comp体系结构类,并且在从十进制数转换为二进制数(双向带符号数)方面存在一些问题.一切正常,直到最后一点,因为我的当前算法在1 << = 31时落入int的界限区域.只需要朝着正确的方向轻推即可启动并运行.谢谢!
//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;
}
Run Code Online (Sandbox Code Playgroud)
我还包括我的其他算法的完整性.我为缺乏评论而道歉,但这是相当直接的.
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;
}
Run Code Online (Sandbox Code Playgroud)
此外,如果有人知道任何好的方法来更有效地写这些,我很乐意听到它.我只有两个入门编程课程,但一直在玩不同的技术,看看我喜欢他们的风格.
Pot*_*ter 65
实际上有这些标准的单行.
#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();
Run Code Online (Sandbox Code Playgroud)
代替:
if((mask&a) >= 1)
Run Code Online (Sandbox Code Playgroud)
与以下任一:
if ((mask & a) != 0)
Run Code Online (Sandbox Code Playgroud)
或者:
if (mask & a)
Run Code Online (Sandbox Code Playgroud)
你的问题是最后一位给你一个负数,而不是一个正数。