Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cmath>
- using std::cin;
- using std::cout;
- using std::endl;
- int convert_bin_to_dec(const char char_num[], int size);
- //Assumes that char_num[] is a C style string terminated by the '/0' character.
- int main()
- {
- int test_size1 = 5, test_size2 = 9;
- char test_num1[5] = { '1', '0', '1', '0', '/0'};
- char test_num2[9] = { '0', '1', '1', '0', '1', '0', '1', '1', '/0'};
- int test_result1 = convert_bin_to_dec(test_num1, test_size1);
- int test_result2 = convert_bin_to_dec(test_num2, test_size2);
- cout << "1010 converted to " << test_result1 << endl;
- cout << "01101011 converted to " << test_result2 << endl;
- return 0;
- }
- int convert_bin_to_dec(const char char_num[], int size)
- {
- int increment = 0, decimal = 0;
- std::vector<int> int_num(size-1);
- std::vector<int>::reverse_iterator rnum_iterator;
- for(int i=0; i<size-1; i++)
- int_num.push_back(char_num[i] - '0');
- for(rnum_iterator = int_num.rbegin(); rnum_iterator != int_num.rend(); rnum_iterator++)
- {
- if(increment==0 && *rnum_iterator == 1)
- decimal += 1;
- else if(increment!=0 && *rnum_iterator == 1)
- decimal += pow(2, increment);
- increment++;
- }
- return decimal;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement