Public paste
asdf
By: asdf | Date: Nov 22 2007 00:36 | Format: C++ | Expires: never | Size: 1.49 KB | Hits: 1336

  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4.  
  5.  
  6. using namespace std;
  7.  
  8.  
  9. string dectobin(int num,int base,int byte);
  10. //string convert(int bits);
  11.  
  12.  
  13. int main()
  14. {
  15.           ifstream inFile; //input file stream
  16.       ofstream outFile; //output file stream
  17.      
  18.       inFile.open("input6.txt"); //open input file
  19.       outFile.open("output6.txt"); //open output file
  20.      int decimalnum;
  21.      int bit;
  22.      int base;
  23.  
  24.  
  25.      base = 2;
  26. /*
  27.            if(!outFile) //check for errors in output file
  28.       {
  29.             cout<<"Cannot open output file!"<<endl;
  30.  
  31.             }
  32.               if(!inFile)
  33.       {
  34.             cout<<"Cannot open input file!"<<endl; //check for errors for input file
  35.  
  36.       } else
  37.    */  
  38.       inFile >>bit;
  39.      cout << endl;
  40.      do
  41. {
  42.      inFile >>decimalnum;
  43.        //convert(decimalnum, base);
  44.      outFile<<"Decimal: "<<decimalnum<<" = " << dectobin(decimalnum, base, bit) << " Binary" <<endl;
  45.      cin >> base;
  46.      outFile<<endl;
  47.  
  48.    
  49.  
  50. }
  51. while(!inFile.eof());
  52.  
  53.       inFile.close(); //close input file
  54.       outFile.close(); //close output file
  55.  
  56.      return 0;
  57.  
  58. }
  59.  
  60.  
  61. string dectobin(int dec, int base,int byte)
  62. {
  63.    
  64.  
  65.  
  66.  
  67.  
  68.      unsigned short num = (unsigned short)(short)dec;
  69.      string  bin(byte, '0');
  70.      unsigned short dig;
  71.      for (int i = byte - 1; i >= 0; --i)
  72.      {
  73.          dig    = (num % base);
  74.          bin[i] = (char)dig + '0';
  75.          num   /= base;
  76.      }
  77.      return bin;
  78. }