I want to convert between the following to formats:
#include <bitset>
std::bitset<4> input[192]; // (4 * 192 bits = 768 bits)
char output[4][24]; // (4 * 24 bytes = 768 bits)
Specifically, I would like to convert each of the four bits, in the bitset
s, as separated char[24]
arrays.
How would do that the easiest and the fastest way?
I would simply use a nested for loop:
constexpr int kSize1 = 4;
constexpr int kSize2 = 24;
constexpr int kBitsPerChar = 8;
void convert(std::array<std::bitset<kSize1>, kSize2 * kBitsPerChar> &input,
std::array<std::array<char, kSize2>, kSize1> &output)
{
for (int i = 0; i < kSize1; ++i)
{
for (int j = 0; j < kSize2; ++j)
{
char &c = output[i][j];
c = 0;
for (int bit = 0; bit < kBitsPerChar; ++bit)
{
c |= input[j * kBitsPerChar + bit][i] << bit;
}
}
}
}
What I did to make it reasonably safe is defining constants for all dimensions, which I use in both the array declarations and the for loop. You should choose more meaningful names than kSize1
, depending on your context.
The line that actually "does the work" is quite straight forward: I fetch one bit from the source array, shift it to the correct position within the current char and update the destination array.