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

顺便说它很复杂,但我尽我所能。

编辑 – 这是我最终使用的解决scheme:

 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 ,用二进制表示前导零填充。

根据需要为数据select位集的宽度,例如std::bitset<32>从32位整数中获取32个字符的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; } 

编辑:请不要编辑我的答案八进制和hex。 OP特别要求Decimal To Binary。

以下是一个recursion函数,它采用一个正整数并将其二进制数字打印到控制台。

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

学分到UoA ENGGEN 131

*注意:使用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 :: bitset将数字转换为二进制格式。

使用下面的代码片段:

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

我发现这在stackoverflow本身。 我附上链接 。

非recursion解决scheme:

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

另一个使用std :: bitset像别人build议的那样。

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

一个intvariables不是十进制的,它是二进制的。 你正在寻找的是一个数字的二进制string表示forms,你可以通过应用一个掩码来过滤各个位,然后打印它们:

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

如果您的问题是algorithm,那就是解决scheme。 如果没有,你应该使用std :: bitset类为你处理:

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

你想要做的事情如:

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

十进制二进制不使用arrays*由Oya提出:

我仍然是一个初学者,所以这段代码将只使用循环和variablesxD …

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

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

这里使用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'; } 

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

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

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

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