#include <stdio.h>
#include <stdint.h>
// Helper function to print binary representation
void print_binary(uint16_t value, int bits) {
for (int i = bits - 1; i >= 0; i--) {
printf("%c", (value
& (1 << i
)) ? '1' : '0'); // Print '1' if bit is set, otherwise '0' }
}
// Simulate reading bits in big-endian order
uint32_t read_bits(uint16_t *bit_buffer, int *bits_left, int num_bits) {
print_binary(*bit_buffer, 16); // Print 16 bits
uint32_t value = *bit_buffer >> (*bits_left - num_bits); // Extract the top `num_bits` bits
*bits_left -= num_bits; // Reduce the count of available bits
*bit_buffer &= (1 << *bits_left) - 1; // Clear the extracted bits
return value; // Return the extracted value
}
int main() {
uint16_t bit_buffer = 0b1101011011110010; // Example big-endian buffer
int bits_left = 16; // Total number of bits available in the buffer
printf("Initial bit_buffer: 0b"); print_binary(bit_buffer, 16); // Print 16 bits
// Read 5 bits
int num_bits = 5;
uint32_t result = read_bits(&bit_buffer, &bits_left, num_bits);
printf("Read %d bits: 0b", num_bits
); print_binary(result, num_bits); // Print 5 bits
printf("Remaining bit_buffer: 0b"); print_binary(bit_buffer, bits_left); // Print remaining bits
printf(", bits_left: %d\n", bits_left
);
// Read another 6 bits
num_bits = 6;
result = read_bits(&bit_buffer, &bits_left, num_bits);
printf("Read %d bits: 0b", num_bits
); print_binary(result, num_bits); // Print 6 bits
printf("Remaining bit_buffer: 0b"); print_binary(bit_buffer, bits_left); // Print remaining bits
printf(", bits_left: %d\n", bits_left
);
// Read the remaining 5 bits
num_bits = 5;
result = read_bits(&bit_buffer, &bits_left, num_bits);
printf("Read %d bits: 0b", num_bits
); print_binary(result, num_bits); // Print 5 bits
printf("Remaining bit_buffer: 0b"); print_binary(bit_buffer, bits_left); // Print remaining bits
printf(", bits_left: %d\n", bits_left
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRpbnQuaD4KCi8vIEhlbHBlciBmdW5jdGlvbiB0byBwcmludCBiaW5hcnkgcmVwcmVzZW50YXRpb24Kdm9pZCBwcmludF9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