This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Mar 14th, 2013  |  syntax: C++  |  size: 1.29 KB  |  views: 52  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data