Advertisement
Guest User

Untitled

a guest
Mar 14th, 2013
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. using std::cin;
  5. using std::cout;
  6. using std::endl;
  7.  
  8. int convert_bin_to_dec(const char char_num[], int size);
  9. //Assumes that char_num[] is a C style string terminated by the '/0' character.
  10.  
  11. int main()
  12. {
  13.     int test_size1 = 5, test_size2 = 9;
  14.     char test_num1[5] = { '1', '0', '1', '0', '/0'};
  15.     char test_num2[9] = { '0', '1', '1', '0', '1', '0', '1', '1', '/0'};
  16.     int test_result1 = convert_bin_to_dec(test_num1, test_size1);
  17.     int test_result2 = convert_bin_to_dec(test_num2, test_size2);
  18.  
  19.     cout << "1010 converted to " << test_result1 << endl;
  20.     cout << "01101011 converted to " << test_result2 << endl;
  21.  
  22.     return 0;
  23. }
  24.  
  25. int convert_bin_to_dec(const char char_num[], int size)
  26. {
  27.     int increment = 0, decimal = 0;
  28.     std::vector<int> int_num(size-1);
  29.     std::vector<int>::reverse_iterator rnum_iterator;
  30.  
  31.     for(int i=0; i<size-1; i++)
  32.         int_num.push_back(char_num[i] - '0');
  33.  
  34.     for(rnum_iterator = int_num.rbegin(); rnum_iterator != int_num.rend(); rnum_iterator++)
  35.     {
  36.         if(increment==0 && *rnum_iterator == 1)
  37.             decimal += 1;
  38.         else if(increment!=0 && *rnum_iterator == 1)
  39.             decimal += pow(2, increment);
  40.  
  41.         increment++;
  42.     }
  43.  
  44.     return decimal;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement