C++ - 十进制到二进制转换

use*_*487 61 c++ binary decimal

我写了一个'简单'(我花了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;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下它很复杂,但我尽我所能.

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

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

Bra*_*don 117

std::bitset有一个.to_string()方法,返回一个std::string二进制文本表示,前导零填充.

根据数据需要选择bitset的宽度,例如std::bitset<32>从32位整数中获取32个字符的字符串.

#include <iostream>
#include <bitset>

int main()
{
    std::string binary = std::bitset<8>(128).to_string(); //to binary
    std::cout<<binary<<"\n";

    unsigned long decimal = std::bitset<8>(binary).to_ulong();
    std::cout<<decimal<<"\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:请不要编辑Octal和Hexadecimal的答案.OP专门要求Decimal To Binary.

  • 对于那些寻求十六进制转换的用户,请使用:`itoa`:http://www.cplusplus.com/reference/cstdlib/itoa/ (2认同)

Pat*_*der 45

以下是递归函数,它采用正整数并将其二进制数字打印到控制台.

Alex建议,为了提高效率,您可能希望printf()将结果删除并存储在内存中......取决于存储方法结果可能会被逆转.

/**
 * Takes a unsigned integer, converts it into binary and prints it to the console.
 * @param n the number to convert and print
 */
void convertToBinary(unsigned int n)
{
    if (n / 2 != 0) {
        convertToBinary(n / 2);
    }
    printf("%d", n % 2);
}
Run Code Online (Sandbox Code Playgroud)

致UoA ENGGEN 131的致谢

*注意:使用unsigned int的好处是它不能是负数.

  • 您可能希望将`n`参数设为`unsigned int`,因为该函数对负数不起作用. (6认同)

skp*_*o19 10

您可以使用std :: bitset将数字转换为二进制格式.

使用以下代码段:

std::string binary = std::bitset<8>(n).to_string();
Run Code Online (Sandbox Code Playgroud)

我在stackoverflow本身发现了这个.我正在附上链接.

  • 或多或少是[已接受答案]的副本(http://stackoverflow.com/a/22746526/224132). (4认同)

小智 7

打印二进制文件非常直接的解决方案:

#include <iostream.h>

int main()
{
 int num,arr[64];
 cin>>num;
 int i=0,r;
 while(num!=0)
{
  r = num%2;
  arr[i++] = r;
  num /= 2;
}

for(int j=i-1;j>=0;j--)
 cout<<arr[j];
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

一个int变量是不是小数,它的二进制。您正在寻找的是数字的二进制字符串表示形式,您可以通过应用过滤单个位的掩码然后打印它们来获得它:

for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
    cout << value & (1 << i) ? '1' : '0';
Run Code Online (Sandbox Code Playgroud)

如果您的问题是算法问题,那就是解决方案。如果没有,您应该使用std::bitset类来为您处理:

bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
Run Code Online (Sandbox Code Playgroud)


Vla*_*cow 5

这里有两种方法。一个类似于你的方法

#include <iostream>
#include <string>
#include <limits>
#include <algorithm>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        const unsigned long long base = 2;

        std::string s;
        s.reserve( std::numeric_limits<unsigned long long>::digits ); 

        do { s.push_back( x % base + '0' ); } while ( x /= base );

        std::cout << std::string( s.rbegin(), s.rend() )  << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个使用 std::bitset 就像其他人建议的那样。

#include <iostream>
#include <string>
#include <bitset>
#include <limits>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        std::string s = 
            std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();

        std::string::size_type n = s.find( '1' ); 
        std::cout << s.substr( n )  << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)


abe*_*312 5

非递归解决方案:

#include <iostream>
#include<string>


std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}
int main()
{
    std::string i= toBinary(10);
    std::cout<<i;
}
Run Code Online (Sandbox Code Playgroud)

递归解决方案:

#include <iostream>
#include<string>

std::string r="";
std::string toBinary(int n)
{
    r=(n%2==0 ?"0":"1")+r;
    if (n / 2 != 0) {
        toBinary(n / 2);
    }
    return r;
}
int main()
{
    std::string i=toBinary(10);
    std::cout<<i;
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*ias 0

你想做类似的事情:

cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1
Run Code Online (Sandbox Code Playgroud)

  • “setbase”可接受的值为“16”、“8”和“10”。任何其他值都会将基字段重置为零(十进制输出和前缀相关输出)。有关更多详细信息,请参阅此参考:[std::setbase - cpprefernce.com](http://en.cppreference.com/w/cpp/io/manip/setbase) (6认同)