C - 十进制到二进制转换

新手上路,请多包涵

我写了一个“简单”(花了我 30 分钟)程序,将十进制数转换为二进制数。我确信有很多更简单的方法,你能告诉我吗?这是代码:

 #include <iostream>
#include <stdlib.h>

using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
    system("clear");
    cout << "Enter a decimal number: ";
    cin >> a1;
    a2 = a1; //we need our number for later on so we save it in another variable

    while (a1!=0) //dividing by two until we hit 0
    {
        remainder = a1%2; //getting a remainder - decimal number(1 or 0)
        a1 = a1/2; //dividing our number by two
        maxtab++; //+1 to max elements of the table
    }

    maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
    a1 = a2; //we must do calculations one more time so we're gatting back our original number
    table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)

    while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
    {
        remainder = a1%2; //getting a remainder
        a1 = a1/2; //dividing by 2
        table[tab] = remainder; //adding 0 or 1 to an element
        tab++; //tab (element count) increases by 1 so next remainder is saved in another element
    }

    tab--; //same as with maxtab--
    cout << "Your binary number: ";

    while (tab>=0) //until we get to the 0 (1st) element of the table
    {
        cout << table[tab] << " "; //write the value of an element (0 or 1)
        tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
    }

    cout << endl;
    return 0;
}

顺便说一句,这很复杂,但我尽力了。

编辑 - 这是我最终使用的解决方案:

 std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}

原文由 user3478487 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 456
1 个回答

或者您可以只使用 atoi()itoa()

在我的情况下,我需要 8 位二进制 [与 MFC 一起使用]

 CString DecToBinStr(int iVal)
{
  CString strTmp;
  int iTmp;

  itoa(iVal, strTmp.GetBuffer(8), 2); // convert to binary
  iTmp = atoi(strTmp);
  strTmp.Format("%08d", iTmp);

  return strTmp;
}

用法:

 CString str_X;
str_X = DecToBinStr(5); // 00000101

原文由 Zarina Abdibaitova 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题