1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
int main() {
std::vector<char> vHex{ '4','8','6','5','6','C','6','C', '6','F' };
std::vector<size_t> hexBits_vec;
std::vector<size_t> allBits_vec;
int decVal{ 0 };
for (auto a : vHex) {
switch (a) {
case 'a':
case'A':
decVal = 10; break;
case 'b':
case'B':
decVal = 11; break;
case 'c':
case'C':
decVal = 12; break;
case 'd':
case'D':
decVal = 13; break;
case 'e':
case'E':
decVal = 14; break;
case 'f':
case'F':
decVal = 15; break;
default: decVal = static_cast<int>(a - '0'); break;
}
while (decVal > 0) { // compute binary values for each hex char
hexBits_vec.push_back(decVal % 2);
decVal /= 2;
}
while (hexBits_vec.size() < 4) // fill up 4 bits for each hex value
hexBits_vec.push_back(0);
std::reverse(hexBits_vec.begin(), hexBits_vec.end()); // put to right order
for (auto i : hexBits_vec)
allBits_vec.push_back(i);
hexBits_vec.clear(); // ready for next hex char
}
decVal = 0;
int byte_count{ 0 }, pw{ 7 }; // pw is the power of each bit in a byte, from right to left {7, 6, ..., 0}
std::vector<bool> bin_to_char_vec;
for (auto a : allBits_vec) {
bin_to_char_vec.push_back(a);
if (++byte_count % 8 == 0) {
for (auto bit : bin_to_char_vec)
decVal += bit * pow(2, pw--);
std::cout << static_cast<char> (decVal);
// Set defaults
pw = 7;
decVal = 0;
bin_to_char_vec.clear();
}
}
std::cout << '\n';
return 0;
}
| |