ビットフィドルを使用してそれを行うことができます:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned char source[3] = { 15, 85, 51 };
unsigned char destination[4];
memset(destination, 0, 4);
for (int i = 0; i < (8 * 3); ++i)
{
destination[i / 6] |= ((source[i / 8] >> (i % 8) & 1) << (i % 6));
}
for (int j = 0; j < 4; ++j)
printf("%d ", destination[j]);
}
出力:
15 20 53 12
これは最下位5ビットから機能し始めることに注意してください。
15 85 51
11110000 10101010 11001100
111100 001010 101011 001100
15 20 53 12
最も重要なものを最初に取得するには、代わりに次のようにします。
destination[i / 6] |= ((source[i / 8] >> (7 - (i % 8))) & 1) << (5 - (i % 6));
これは、最上位ビットを最初に書いたと仮定して、例のように機能します。
240 170 204
11110000 10101010 11001100
111100 001010 101011 001100
60 10 43 12