I have implemented a sample program that converts vector of characters to its integer representation depending on the bit size specified. I was hoping to get some input on how to simplify the sequence. I think my approach is convoluted.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <iterator>
int OctalToBinary(int octalNum) {
int decimalNum = 0, binaryNum = 0, count = 0;
while (octalNum != 0) {
decimalNum += (octalNum % 10) * pow(8, count);
++count;
octalNum /= 10;
}
count = 1;
while (decimalNum != 0) {
binaryNum += (decimalNum % 2) * count;
decimalNum /= 2;
count *= 10;
}
return binaryNum;
}
int main()
{
std::vector<char> buffer = { '3','7','4','3','0'};
std::vector<int> bitsize = { 3,3,8 };
std::vector<char> collection;
std::vector<std::string> output;
// convert characters to octal and
for each ( char c in buffer)
{
int x = c - '0';
std::stringstream opt;
opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";
std::string val = opt.str();
std::copy(val.begin(), val.end()-1, std::back_inserter(collection));
}
int start_index = 0;
int end_index = 0;
// convert binary values to integer
for (int i = 0; i < bitsize.size(); i++)
{
start_index = end_index;
end_index += bitsize[i];
std::string temporary_string(collection.begin() + start_index, collection.begin() + end_index);
int converted_integer = std::stoi(temporary_string.c_str(), nullptr, 2);
std::cout << temporary_string << " " << converted_integer << "\n";
}
// output should be 3, 7 , 140
int x;
std::cin >> x;
return 0;
}