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

时间:2014-03-30 16:20:31

标签: 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;
}

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

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

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

29 个答案:

答案 0 :(得分:104)

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

根据数据的需要选择位集的宽度,例如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;
}

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

答案 1 :(得分:43)

以下是一个递归函数,它接受一个正整数并将其二进制数字打印到控制台。

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

/**
 * Takes a positive 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);
}

对UoA ENGGEN 131的信用

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

答案 2 :(得分:8)

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

使用以下代码段:

std::string binary = std::bitset<8>(n).to_string();

我在stackoverflow上发现了这个。我附上了link

答案 3 :(得分: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];
}

答案 4 :(得分:4)

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

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

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

bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();

答案 5 :(得分:4)

非递归解决方案:

#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;
}

递归解决方案:

#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;
}

答案 6 :(得分:3)

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

#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;
    }
}

,另一个使用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;
    }
}

答案 7 :(得分:0)

下面是简单的C代码,它将二进制转换为十进制然后再次返回。我是在很久以前为一个项目写的,该项目的目标是嵌入式处理器,而开发工具的stdlib对于固件ROM来说很大

这是通用C代码,不使用任何库,也不使用除法或余数(%)运算符(在某些嵌入式处理器上比较慢),也不使用任何浮点,也不使用任何查表也不模拟任何BCD算法。它使用的是类型long long,更具体地说是unsigned long long(或uint64),因此,如果您的嵌入式处理器(及其附带的C编译器)不能执行64-位整数算术,此代码不适用于您的应用程序。否则,我认为这是生产质量C代码(可能是在将long更改为int32并将unsigned long long更改为uint64之后)。我已经整夜运行了此程序,以对每个2 ^ 32个有符号整数值进行测试,并且在任何方向上转换都没有错误。

我们有一个C编译器/链接器,它可以生成可执行文件,我们需要做 而无需任何stdlib(这是猪)。因此,既没有printf()也没有scanf()。甚至没有sprintf()也没有sscanf()。但是,我们仍然具有用户界面,必须将以10为基数的数字转换为二进制,然后再转换为二进制。 (我们还组成了自己的类似malloc()的实用程序,也构造了自己的先验数学函数。)

这就是我的操作方式(main程序和对stdlib的调用可以在我的Mac上测试此东西,对于嵌入式代码,不是)。另外,由于某些较旧的dev系统无法识别“ int64”和“ uint64”以及类似类型,因此使用类型long longunsigned long long并假定它们是相同。并且long被假定为32位。我想我可以typedef编辑它。

// returns an error code, 0 if no error,
// -1 if too big, -2 for other formatting errors
int decimal_to_binary(char *dec, long *bin)
    {
    int i = 0;

    int past_leading_space = 0;
    while (i <= 64 && !past_leading_space)        // first get past leading spaces
        {
        if (dec[i] == ' ')
            {
            i++;
            }
         else
            {
            past_leading_space = 1;
            }
        }
    if (!past_leading_space)
        {
        return -2;                                // 64 leading spaces does not a number make
        }
    // at this point the only legitimate remaining
    // chars are decimal digits or a leading plus or minus sign

    int negative = 0;
    if (dec[i] == '-')
        {
        negative = 1;
        i++;
        }
     else if (dec[i] == '+')
        {
        i++;                                    // do nothing but go on to next char
        }
    // now the only legitimate chars are decimal digits
    if (dec[i] == '\0')
        {
        return -2;                              // there needs to be at least one good 
        }                                       // digit before terminating string

    unsigned long abs_bin = 0;
    while (i <= 64 && dec[i] != '\0')
        {
        if ( dec[i] >= '0' && dec[i] <= '9' )
            {
            if (abs_bin > 214748364)
                {
                return -1;                                // this is going to be too big
                }
            abs_bin *= 10;                                // previous value gets bumped to the left one digit...                
            abs_bin += (unsigned long)(dec[i] - '0');     // ... and a new digit appended to the right
            i++;
            }
         else
            {
            return -2;                                    // not a legit digit in text string
            }
        }

    if (dec[i] != '\0')
        {
        return -2;                                // not terminated string in 64 chars
        }

    if (negative)
        {
        if (abs_bin > 2147483648)
            {
            return -1;                            // too big
            }
        *bin = -(long)abs_bin;
        }
     else
        {
        if (abs_bin > 2147483647)
            {
            return -1;                            // too big
            }
        *bin = (long)abs_bin;
        }

    return 0;
    }


void binary_to_decimal(char *dec, long bin)
    {
    unsigned long long acc;                // 64-bit unsigned integer

    if (bin < 0)
        {
        *(dec++) = '-';                    // leading minus sign
        bin = -bin;                        // make bin value positive
        }

    acc = 989312855LL*(unsigned long)bin;        // very nearly 0.2303423488 * 2^32
    acc += 0x00000000FFFFFFFFLL;                 // we need to round up
    acc >>= 32;
    acc += 57646075LL*(unsigned long)bin;
    // (2^59)/(10^10)  =  57646075.2303423488  =  57646075 + (989312854.979825)/(2^32)  

    int past_leading_zeros = 0;
    for (int i=9; i>=0; i--)            // maximum number of digits is 10
        {
        acc <<= 1;
        acc += (acc<<2);                // an efficient way to multiply a long long by 10
//      acc *= 10;

        unsigned int digit = (unsigned int)(acc >> 59);        // the digit we want is in bits 59 - 62

        if (digit > 0)
            {
            past_leading_zeros = 1;
            }

        if (past_leading_zeros)
            {
            *(dec++) = '0' + digit;
            }

        acc &= 0x07FFFFFFFFFFFFFFLL;    // mask off this digit and go on to the next digit
        }

    if (!past_leading_zeros)            // if all digits are zero ...
        {
        *(dec++) = '0';                 // ... put in at least one zero digit
        }

    *dec = '\0';                        // terminate string
    }


#if 1

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin, result1, result2;
    unsigned long num_errors;
    long long long_long_bin;

    num_errors = 0;
    for (long_long_bin=-2147483648LL; long_long_bin<=2147483647LL; long_long_bin++)
        {
        bin = (long)long_long_bin;
        if ((bin&0x00FFFFFFL) == 0)
            {
            printf("bin = %ld \n", bin);        // this is to tell us that things are moving along
            }
        binary_to_decimal(dec, bin);
        decimal_to_binary(dec, &result1);
        sscanf(dec, "%ld", &result2);            // decimal_to_binary() should do the same as this sscanf()

        if (bin != result1 || bin != result2)
            {
            num_errors++;
            printf("bin = %ld, result1 = %ld, result2 = %ld, num_errors = %ld, dec = %s \n",
                bin, result1, result2, num_errors, dec);
            }
        }

    printf("num_errors = %ld \n", num_errors);

    return 0;
    }

#else

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin;

    printf("bin = ");
    scanf("%ld", &bin);
    while (bin != 0)
        {
        binary_to_decimal(dec, bin);
        printf("dec = %s \n", dec);
        printf("bin = ");
        scanf("%ld", &bin);
        }

    return 0;
    }

#endif

答案 8 :(得分:0)

使用位掩码,按位和。

string int2bin(int n){
    string x;
    for(int i=0;i<32;i++){
        if(n&1) {x+='1';}
        else {x+='0';}
        n>>=1;
    }
    reverse(x.begin(),x.end());
    return x;
}

答案 9 :(得分:0)

#include <iostream>
#include <bitset>

#define bits(x)  (std::string( \
            std::bitset<8>(x).to_string<char,std::string::traits_type, std::string::allocator_type>() ).c_str() )


int main() {

   std::cout << bits( -86 >> 1 ) << ": " << (-86 >> 1) << std::endl;

   return 0;
}

答案 10 :(得分:0)

我在C ++中将十进制转换为二进制的方式。但是由于我们使用的是mod,因此该功能在十六进制或八进制的情况下也可以使用。您也可以指定位。此函数将继续计算最低有效位并将其放在字符串的末尾。如果您与这种方法不太相似,可以访问:https://www.wikihow.com/Convert-from-Decimal-to-Binary

#include <bits/stdc++.h>
using namespace std;

string itob(int bits, int n) {
    int c;
    char s[bits+1]; // +1 to append NULL character.

    s[bits] = '\0'; // The NULL character in a character array flags the end of the string, not appending it may cause problems.

    c = bits - 1; // If the length of a string is n, than the index of the last character of the string will be n - 1. Cause the index is 0 based not 1 based. Try yourself.

    do {
        if(n%2) s[c] = '1';
        else s[c] = '0';
        n /= 2;
        c--;
    } while (n>0);

    while(c > -1) {
        s[c] = '0';
        c--;
}

    return s;
}

int main() {
    cout << itob(1, 0) << endl; // 0 in 1 bit binary.
    cout << itob(2, 1) << endl; // 1 in 2 bit binary.
    cout << itob(3, 2) << endl; // 2 in 3 bit binary.
    cout << itob(4, 4) << endl; // 4 in 4 bit binary.
    cout << itob(5, 15) << endl; // 15 in 5 bit binary.
    cout << itob(6, 30) << endl; // 30 in 6 bit binary.
    cout << itob(7, 61) << endl; // 61 in 7 bit binary.
    cout << itob(8, 127) << endl; // 127 in 8 bit binary.
    return 0;
}

输出:

0
01
010
0100
01111
011110
0111101
01111111

答案 11 :(得分:0)

好的。我可能不是C ++的新手,但是我觉得上面的示例并不能很好地完成工作。

这是我对这种情况的看法。

char* DecimalToBinary(unsigned __int64 value, int bit_precision)
{
    int length = (bit_precision + 7) >> 3 << 3;
    static char* binary = new char[1 + length];
    int begin = length - bit_precision;
    unsigned __int64 bit_value = 1;
    for (int n = length; --n >= begin; )
    {
        binary[n] = 48 | ((value & bit_value) == bit_value);
        bit_value <<= 1;
    }
    for (int n = begin; --n >= 0; )
        binary[n] = 48;

    binary[length] = 0;
    return binary;
}

@value =我们正在检查的值。

@bit_precision =要检查的最左边的最高位。

@Length =最大字节块大小。例如。 7 = 1字节和9 = 2字节,但是我们以位的形式表示,因此1 Byte = 8位。

@binary =我给我们用来设置我们所设置的字符数组的一些哑巴名称。我们将此设置为静态,这样就不会在每次调用时都重新创建它。为了简单地获取结果并显示它,这很好用,但是如果您要在UI上显示多个结果,它们将全部显示为最后一个结果。可以通过删除static来解决此问题,但是请确保在完成操作后删除[]结果。

@begin =这是我们正在检查的最低索引。超出此点的所有内容都将被忽略。或如第二循环所示,将其设置为0。

@first循环-在这里,我们将值设置为48,并根据(value&bit_value)== bit_value的布尔值将0或1基本上添加到48。如果为true,则将char设置为49。如果为false,则将char设置为48。然后,将bit_value移位或基本上乘以2。

@second循环-在这里,我们将所有被忽略的索引设置为48或'0'。

某些示例输出!

int main()
{
    int val = -1;
    std::cout << DecimalToBinary(val, 1) << '\n';
    std::cout << DecimalToBinary(val, 3) << '\n';
    std::cout << DecimalToBinary(val, 7) << '\n';
    std::cout << DecimalToBinary(val, 33) << '\n';
    std::cout << DecimalToBinary(val, 64) << '\n';
    std::cout << "\nPress any key to continue. . .";
    std::cin.ignore();
    return 0;
}

00000001 //Value = 2^1 - 1
00000111 //Value = 2^3 - 1.
01111111 //Value = 2^7 - 1.
0000000111111111111111111111111111111111 //Value = 2^33 - 1.
1111111111111111111111111111111111111111111111111111111111111111 //Value = 2^64 - 1.

速度测试

原始问题的答案:“方法:toBinary(int);”

执行:10,000次,总时间(以毫秒为单位):4701.15,平均时间(以纳秒为单位):470114

我的版本:“方法:DecimalToBinary(int,int);”

//使用64位精度。

执行:10,000,000,总时间(毫秒):3386,平均时间(纳秒):338

//使用1位精度。

执行次数:10,000,000,总时间(毫秒):634,平均时间(纳秒):63

答案 12 :(得分:0)

#include <iostream>

// x is our number to test
// pow is a power of 2 (e.g. 128, 64, 32, etc...)
int printandDecrementBit(int x, int pow)
{
    // Test whether our x is greater than some power of 2 and print the bit
    if (x >= pow)
    {
        std::cout << "1";
        // If x is greater than our power of 2, subtract the power of 2
        return x - pow;
    }
    else
    {
        std::cout << "0";
        return x;
    }
}

int main()
{
    std::cout << "Enter an integer between 0 and 255: ";
    int x;
    std::cin >> x;

    x = printandDecrementBit(x, 128);
    x = printandDecrementBit(x, 64);
    x = printandDecrementBit(x, 32);
    x = printandDecrementBit(x, 16);

    std::cout << " ";

    x = printandDecrementBit(x, 8);
    x = printandDecrementBit(x, 4);
    x = printandDecrementBit(x, 2);
    x = printandDecrementBit(x, 1);

    return 0;
}

这是获取int二进制形式的简单方法。归功于learningcpp.com。我肯定可以用不同的方式来达到目的。

答案 13 :(得分:0)

这是现代变体,可以用于let saveQuestion = UserDefaults.standard.bool(forKey: "SaveQuestion") if (saveQuestion){ ref.child("QuestionOfUsers").childByAutoId().setValue(label1.text) label1.text = "" } 个不同大小的东西。

ints

答案 14 :(得分:0)

在这种方法中,十进制将转换为字符串formate中的相应二进制数。选择字符串返回类型是因为它可以处理更多范围的输入值。

class Solution {
public:
  string ConvertToBinary(int num) 
  {
    vector<int> bin;
    string op;
    for (int i = 0; num > 0; i++)
    {
      bin.push_back(num % 2);
      num /= 2;
    }
    reverse(bin.begin(), bin.end());
    for (size_t i = 0; i < bin.size(); ++i)
    {
      op += to_string(bin[i]);
    }
    return op;
  }
};

答案 15 :(得分:0)

从自然数到二进制字符串的转换:

string toBinary(int n) {
    if (n==0) return "0";
    else if (n==1) return "1";
    else if (n%2 == 0) return toBinary(n/2) + "0";
    else if (n%2 != 0) return toBinary(n/2) + "1";
}

答案 16 :(得分:0)

您的解决方案需要修改。最后的字符串应在返回之前反转:

std::reverse(r.begin(), r.end());
return r;

答案 17 :(得分:0)

你想做类似的事情:

cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1

答案 18 :(得分:0)

为此,在C ++中可以使用itoa()函数。此函数将任何十进制整数转换为二进制,十进制,十六进制和八进制数。

#include<bits/stdc++.h>
using namespace std;
int main(){
 int a;    
 char res[1000];
 cin>>a;
 itoa(a,res,10);
 cout<<"Decimal- "<<res<<endl;
 itoa(a,res,2);
 cout<<"Binary- "<<res<<endl;
 itoa(a,res,16);
 cout<<"Hexadecimal- "<<res<<endl;
 itoa(a,res,8);
 cout<<"Octal- "<<res<<endl;return 0;
}

但是,仅特定编译器支持。

您还可以看到:itoa-C++ Reference

答案 19 :(得分:0)

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

参考: - https://www.geeksforgeeks.org/program-decimal-binary-conversion/

或 使用功能: -

#include<bits/stdc++.h>
using namespace std;

int main()
{

    int n;cin>>n;
    cout<<bitset<8>(n).to_string()<<endl;


}

或 使用左移

#include<bits/stdc++.h>
using namespace std;
int main()
{
    // here n is the number of bit representation we want 
    int n;cin>>n;

    // num is a number whose binary representation we want
    int num;
    cin>>num;

    for(int i=n-1;i>=0;i--)
    {
        if( num & ( 1 << i ) ) cout<<1;
        else cout<<0;
    }


}

答案 20 :(得分:0)

std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}

答案 21 :(得分:0)

HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY


  #include<iostream>
    using namespace std;
    int main()
    {
        int input,rem,res,count=0,i=0;
        cout<<"Input number: ";
        cin>>input;`enter code here`
        int num=input;
        while(input > 0)
        {
            input=input/2;  
            count++;
        }

        int arr[count];

        while(num > 0)
        {
            arr[i]=num%2;
            num=num/2;  
            i++;
        }
        for(int i=count-1 ; i>=0 ; i--)
        {
            cout<<" " << arr[i]<<" ";
        }



        return 0;
    }

答案 22 :(得分:0)

import urllib2
from bs4 import BeautifulSoup
import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')

def scrapsl():
    wordlist = []
    deflist = []
    soup = BeautifulSoup(urllib2.urlopen('https://sjp.pl/slownik/lp.phtml?page=1').read(), "html.parser")
    nextpage = soup.find_all('b')[1].a.get('href')
    for i in range(2, 52):
        wordlist.append(unicode(soup.find_all('tr')[i].td.text))
        print(unicode(soup.find_all('tr')[i].td.text))
        sp = BeautifulSoup(urllib2.urlopen('https://sjp.pl/' + str(wordlist[(len(wordlist) - 1)]).replace(' ', "+")).read(), "html.parser")
        deflist.append({wordlist[(len(wordlist) - 1)]: sp.find_all('p')[3].text})
        print(str(i) + "\\52")
    print wordlist
    writelist = []
    writelist.append(wordlist)
    writelist.append(deflist)
    ftw = open("slownik.txt", 'w')
    ftw.write(json.dumps(writelist))
    ftw.close()
scrapsl()

答案 23 :(得分:0)

PersonStore

答案 24 :(得分:0)

实际上有一种非常简单的方法可以做到这一点。我们所做的是使用递归函数,该函数在参数中给出数字(int)。这很容易理解。您也可以添加其他条件/变体。这是代码:

int binary(int num)
{
    int rem;
    if (num <= 1)
        {
            cout << num;
            return num;
        }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
    return rem;
}

答案 25 :(得分:0)

这是一个比以往更简单程序

//Program to convert Decimal into Binary
#include<iostream>
using namespace std;
int main()
{
    long int dec;
    int rem,i,j,bin[100],count=-1;
    again:
    cout<<"ENTER THE DECIMAL NUMBER:- ";
    cin>>dec;//input of Decimal
    if(dec<0)
    {
        cout<<"PLEASE ENTER A POSITIVE DECIMAL";
        goto again;
    }
    else
        {
        cout<<"\nIT's BINARY FORM IS:- ";
        for(i=0;dec!=0;i++)//making array of binary, but reversed
        {
            rem=dec%2;
            bin[i]=rem;
            dec=dec/2;
            count++;
        }
        for(j=count;j>=0;j--)//reversed binary is printed in correct order
        {
            cout<<bin[j];
        }
    }
    return 0; 
}

答案 26 :(得分:0)

这里是一个使用std::string作为容器的简单转换器。它允许负值。

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

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

答案 27 :(得分:0)

由Oya制作的“无法使用的任何阵列”:

我还是初学者,所以这段代码只会使用循环和变量xD ...

希望你喜欢它。这可能比它更简单......

    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main()
    {
        int i;
        int expoentes; //the sequence > pow(2,i) or 2^i
        int decimal; 
        int extra; //this will be used to add some 0s between the 1s
        int x = 1;

        cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
        cout << "\n\nWARNING: Only works until ~1.073 millions\n";
        cout << "     To exit, enter a negative number\n\n";

        while(decimal >= 0){
            cout << "\n----- // -----\n\n";
            cin >> decimal;
            cout << "\n";

            if(decimal == 0){
                cout << "0";
            }
            while(decimal >= 1){
                i = 0;
                expoentes = 1;
                while(decimal >= expoentes){
                    i++;
                    expoentes = pow(2,i);
                }
                x = 1;
                cout << "1";
                decimal -= pow(2,i-x);
                extra = pow(2,i-1-x);
                while(decimal < extra){
                    cout << "0";
                    x++;
                    extra = pow(2,i-1-x);
                }
            }
        }
        return 0;
    }

答案 28 :(得分:-2)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void Decimal2Binary(long value,char *b,int len)
{
    if(value>0)
    {
        do
        {
            if(value==1)
            {
                *(b+len-1)='1';
                break;
            }
            else
            {
                *(b+len-1)=(value%2)+48;
                value=value/2;
                len--;
            }
        }while(1);
    }
}
long Binary2Decimal(char *b,int len)
{
    int i=0;
    int j=0;
    long value=0;
    for(i=(len-1);i>=0;i--)
    {
        if(*(b+i)==49)
        {
            value+=pow(2,j);
        }
        j++;
    }
    return value;
}
int main()
{
    char data[11];//最後一個BIT要拿來當字串結尾
    long value=1023;
    memset(data,'0',sizeof(data));
    data[10]='\0';//字串結尾
    Decimal2Binary(value,data,10);
    printf("%d->%s\n",value,data);
    value=Binary2Decimal(data,10);
    printf("%s->%d",data,value);
    return 0;
}