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
|
uint8_t *binarize(const int *const input, const size_t input_size, size_t *const output_size)
{
// allocate output buffer
// note: required buffer length is the length of the input array divided by eight, but rounded up!
*output_size = (input_size + 7) / 8;
uint8_t *const buffer = (uint8_t*) calloc(*output_size, sizeof(uint8_t));
if (!buffer)
{
return NULL;
}
// fill the output buffer, one bit at a time, moving to the next output byte every eight input values (bits)
uint8_t *out = buffer;
for (size_t i = 0; i < input_size; ++i)
{
// move to next output byte, when the time has come
if (i && (i % 8 == 0))
{
++out;
}
// left-shift the current byte, by one, then set the least significant bit according to input
*out = (*out << 1) | (input[i] ? 0x1 : 0x0); // <-- maps zero input to '0' and any non-zero input to '1'
}
// adjust bit positions of the final (incomplete) byte
if (input_size % 8 != 0)
{
*out <<= 8 - (input_size % 8);
}
return buffer;
}
int main()
{
const int input[26] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 };
// get length of the input array
const size_t input_size = sizeof(input) / sizeof(input[0]);
// convert input sequence to bytes
size_t output_size;
uint8_t *buffer = binarize(input, input_size, &output_size);
if (!buffer)
{
return -1;
}
//print result
for (size_t i = 0; i < output_size; ++i)
{
printf(i ? ",0x%02X" : "0x%02X", buffer[i]);
}
puts("");
// free
free(buffer);
}
|