I'm trying to convert an array of bits to an array of bytes, except my operations seem to be reading my bits in the opposite direction from what I want them to be. For example, say the array of binary bits is 10110111 11000000 00000110. I want the byte array to be {B7, C0, 06}. Instead, my code below produces an output of of {ED, 03, 60} i.e. it reads every 8 bits in the opposite direction. Could anyone provide me some suggestions as to where I am going wrong?
void find_hex_arr(uint8_t* bit_arr, int bit_len) {
uint8_t* hex_arr = malloc(bit_len/8);
int index = 0;
unsigned int i = 0;
unsigned int j = 0;
for (i = 0; i < bit_len; i = j) {
for (j = i; j < i + 8; ++j) {
hex_arr[index] |= bit_arr[j] << (j - i);
}
index++;
}
}
bit_lenis not an integral multiple of 8, yourmallocwill come up short. You want to round up the number of bytes:uint8_t* hex_arr = malloc((bit_len + 7) / 8);