将整数更改为二进制数字字符串

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)

将此运行视为演示.

  • @Chaos_99 那是[不合理的旧](http://gcc.gnu.org/releases.html)。你从哪里得到的? (2认同)
  • 令人惊讶的是,似乎没有人提到bitset的to_string将返回填充的二进制表示.显然,因为bitset返回的集合的二进制表示正是它应该返回的.但如果有人"误用"bitset将int转换为二进制字符串表示,则会调用输出填充.`cout << bitset <16>(21); //输出0000000000010101` (2认同)

Jon*_*ler 5

代替:

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)

你的问题是最后一位给你一个负数,而不是一个正数。