s
By: s | Date: Nov 27 2007 02:30 | Format: C++ | Expires: never | Size: 2.89 KB | Hits: 1278
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <stack>
- using namespace std;
- string dectobin(unsigned int num);
- string convert(int num, int n);
- int main()
- {
- ifstream infile;
- ofstream outfile;
- infile.open("input6.txt");
- outfile.open("ouput6.txt");
- string x;
- int decimalnum;
- int bits;
- infile >> bits;
- if (!infile)
- cout<<"Unable to open file input5.txt";
- while(infile >> decimalnum)
- {
- infile >> decimalnum;
- //cout << decimalnum;
- x = convert(decimalnum,bits);
- outfile << decimalnum << " = " << x << endl; //outputs the value of dectobin
- }
- infile.close();
- outfile.close();
- system("PAUSE");
- return 0;
- }
- string convert(int num, int n)
- {
- string y;
- int num2;
- stack<char> tmpStack;
- stack<char> myStack;
- string tmp;
- bool doIt = false;
- if ( num > 0)
- {
- y = dectobin(num);
- }
- while (y.size() <= n-1 ) // adds 0's
- {
- y = "0" + y;
- }
- if ( num <0)
- {
- num2 = (num*-1);
- tmp = dectobin(num2);
- while (y.size() <= n-1 )// adds 0's
- {
- y = "0" + y;
- }
- for (int k=0;tmp.length(); k++)
- {
- tmpStack.push(tmp[k]);
- }
- while (!tmpStack.empty())
- {
- if (tmpStack.top() == '1' && doIt)
- {
- myStack.push('0');
- tmpStack.pop();
- }
- else
- if (tmpStack.top() == '0' && doIt)
- {
- myStack.push('1');
- tmpStack.pop();
- }
- else
- if (tmpStack.top() == '1' && doIt == false)
- {
- myStack.push('1');
- doIt = true;
- tmpStack.pop();
- }
- else
- if (tmpStack.top() == '0' && doIt == false)
- {
- myStack.push('0');
- tmpStack.pop();
- }
- while (!myStack.empty())
- {
- y += myStack.top();
- myStack.pop();
- }
- }
- }
- return y;
- }
- string dectobin(unsigned int num)
- {
- string b;
- if( num > 0)
- {
- b = dectobin(num/2) +
- static_cast<char>('0'+ (num % 2));
- return b; // <--- return the concatenation
- }
- return ""; // <--- return the empty string (in case num == 0)
- }
Latest pastes
1 hours ago
11 hours ago
1 days ago
2 days ago
2 days ago