//Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86
// convert_to_bits()
#include <bitset>
#include <type_traits>
#include <algorithm>
#include <climits>
// main()
#include <iostream>
#include <sstream>
template<typename FromT, size_t FromSZ, typename ToT, size_t ToSZ>
void convert_to_bits(const FromT (&from_arr)[FromSZ], ToT (&to_arr)[ToSZ]) {
static_assert(ToSZ >= ((sizeof(FromT) * CHAR_BIT) * FromSZ),
"Destination array must have enough elements to contain all bits of source array.");
// Helper value, will be optimised out.
constexpr size_t ELEMENT_SIZE = sizeof(FromT) * CHAR_BIT;
// Handles bit manipulation cleanly.
std::bitset<ELEMENT_SIZE> temp[FromSZ];
// Populate temp.
for (size_t i = 0; i < FromSZ; i++) { temp[i] = from_arr[i]; }
// Fill destination array, one "row" (value in source array) at a time.
for (size_t i = 0; i < FromSZ; i++) {
size_t row = i * ELEMENT_SIZE;
using std::fill;
if (temp[i].none()) {
// Row is all 0s, fill its part of destination array appropriately.
fill(&to_arr[row], &to_arr[row + (ELEMENT_SIZE - 1)], 0);
} else if (temp[i].all()) {
// Row is all 1s, fill its part of destination array appropriately.
fill(&to_arr[row], &to_arr[row + (ELEMENT_SIZE - 1)], 1);
} else {
// Row is mixed, do it one bit at a time.
for (size_t j = 0; j < ELEMENT_SIZE; j++) {
to_arr[row + j] = temp[i][j];
}
}
}
}
template<typename T, size_t N>
constexpr size_t arr_size(T (&arr)[N]) { return N; }
struct Results {
std::stringstream base;
std::stringstream answ;
bool compare() { return base.str() == answ.str(); }
};
int main() {
// Data:
constexpr size_t INT_SZ = sizeof(int) * CHAR_BIT;
int Data[8] = {0,0,190,42,0,0,2,33};
int bits[8 * INT_SZ] = {0};
// -----
// Work:
convert_to_bits(Data, bits);
// -----
// Obtain results, for testing.
Results results;
// Original data.
for (size_t i = 0; i < arr_size(Data); i++) {
for (size_t j = 0; j < INT_SZ; j++) {
results.base << ((Data[i] & (1 << j)) ? 1 : 0);
}
results.base << '\n';
}
results.base << '\n';
// Converted data.
for (size_t i = 0; i < arr_size(bits); i++) {
results.answ << bits[i]
// Mimics results.base's outer loop.
<< ((i + 1) % INT_SZ == 0 ? "\n" : "");
}
results.answ << '\n';
// -----
// Output and compare.
std::cout << "Original data:\n" << results.base.str();
std::cout << "Results:\n" << results.answ.str();
std::cout << "Results are "
<< (results.compare() ? "identical" : "incorrect")
<< ".\n";
}