# C ++ – 十进制到二进制转换

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

`std::bitset`有一个`.to_string()`方法，该方法返回一个`std::string` ，用二进制表示前导零填充。

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

Alexbuild议，为了提高效率，您可能需要删除`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); }` `

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

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

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

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

recursion解决scheme：

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

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

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

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

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

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

` ` #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,ix); extra = pow(2,i-1-x); while(decimal < extra){ cout << "0"; x++; extra = pow(2,i-1-x); } } } return 0; }` `

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

` `//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; }` `

` `int binary(int num) { int rem; if (num <= 1) { cout << num; return num; } rem = num % 2; binary(num / 2); cout << rem; return rem; }` `
` `#include "stdafx.h" #include<iostream> #include<vector> #include<cmath> using namespace std; int main() { // Initialize Variables double x; int xOct; int xHex; //Initialize a variable that stores the order if the numbers in binary/sexagesimal base vector<int> rem; //Get Demical value cout << "Number (demical base): "; cin >> x; //Set the variables xOct = x; xHex = x; //Get the binary value for (int i = 0; x >= 1; i++) { rem.push_back(abs(remainder(x, 2))); x = floor(x / 2); } //Print binary value cout << "Binary: "; int n = rem.size(); while (n > 0) { n--; cout << rem[n]; } cout << endl; //Print octal base cout << oct << "Octal: " << xOct << endl; //Print hexademical base cout << hex << "Hexademical: " << xHex << endl; system("pause"); return 0; }` `

` `#include <iostream> using namespace std; int main(){ int a, i; cin>>a; for(i=0; i<32; i++) if((1<<(31-i) & a)==0) cout<<0; else cout<<1; return 0; }` `
` `#include <iostream> using namespace std; int main() { int a,b; cin>>a; for(int i=31;i>=0;i--) { b=(a>>i)&1; cout<<b; } }` `
` `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; }` `
` `std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}` `
` `#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; }` `