Decimal 2 binary 的转换算法

来源:互联网 发布:幽浮2中文设置 Mac 编辑:程序博客网 时间:2024/05/01 22:36

一直以来自己不怎么懂 十进制转换为二进制,今天彻底的研究了以下,搞定了。

源码如下:

 

 

Code:
  1. #include <iostream>   
  2. #include <fstream>   
  3. #include <string>   
  4. #include <algorithm>   
  5.   
  6. using namespace std;   
  7. string s;// The definition of global value;   
  8. int main(int argc,char *argv[])   
  9. {   
  10.     ifstream cin("aaa.txt");   
  11.     int n;   
  12.     while(cin>>n)   
  13.     {   
  14.         if(0==n)   
  15.         {   
  16.             cout<<"      0-->0/n";   
  17.             continue;   
  18.         }   
  19.         s=" ";   
  20.         for(int a=n; a; a=a/2)   
  21.         {   
  22.             s = s+(a%2 ?'1':'0');   
  23.         }   
  24.         std::reverse(s.begin(),s.end());   
  25.         const char *sss = s.c_str();   
  26.         cout<<n<<(n<0?"-->-":"-->")<<sss<<endl;   
  27.     }   
  28.     return 0;   
  29. }   
  30. /*out put :  
  31.           0-->0  
  32.     12-->1100  
  33.     33-->100001  
  34.     45-->101101  
  35.     2-->10  
  36.     345-->101011001  
  37. */