fork download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. // Helper function to print binary representation
  5. void print_binary(uint16_t value, int bits) {
  6. for (int i = bits - 1; i >= 0; i--) {
  7. printf("%c", (value & (1 << i)) ? '1' : '0'); // Print '1' if bit is set, otherwise '0'
  8. }
  9. }
  10.  
  11. // Simulate reading bits in big-endian order
  12. uint32_t read_bits(uint16_t *bit_buffer, int *bits_left, int num_bits) {
  13. printf("bit_buffer: 0b");
  14. print_binary(*bit_buffer, 16); // Print 16 bits
  15. printf("\n");
  16. uint32_t value = *bit_buffer >> (*bits_left - num_bits); // Extract the top `num_bits` bits
  17. *bits_left -= num_bits; // Reduce the count of available bits
  18. *bit_buffer &= (1 << *bits_left) - 1; // Clear the extracted bits
  19. return value; // Return the extracted value
  20. }
  21.  
  22. int main() {
  23. uint16_t bit_buffer = 0b1101011011110010; // Example big-endian buffer
  24. int bits_left = 16; // Total number of bits available in the buffer
  25.  
  26. printf("Initial bit_buffer: 0b");
  27. print_binary(bit_buffer, 16); // Print 16 bits
  28. printf("\n");
  29.  
  30. // Read 5 bits
  31. int num_bits = 5;
  32. uint32_t result = read_bits(&bit_buffer, &bits_left, num_bits);
  33. printf("Read %d bits: 0b", num_bits);
  34. print_binary(result, num_bits); // Print 5 bits
  35. printf("\n");
  36. printf("Remaining bit_buffer: 0b");
  37. print_binary(bit_buffer, bits_left); // Print remaining bits
  38. printf(", bits_left: %d\n", bits_left);
  39.  
  40. // Read another 6 bits
  41. num_bits = 6;
  42. result = read_bits(&bit_buffer, &bits_left, num_bits);
  43. printf("Read %d bits: 0b", num_bits);
  44. print_binary(result, num_bits); // Print 6 bits
  45. printf("\n");
  46. printf("Remaining bit_buffer: 0b");
  47. print_binary(bit_buffer, bits_left); // Print remaining bits
  48. printf(", bits_left: %d\n", bits_left);
  49.  
  50. // Read the remaining 5 bits
  51. num_bits = 5;
  52. result = read_bits(&bit_buffer, &bits_left, num_bits);
  53. printf("Read %d bits: 0b", num_bits);
  54. print_binary(result, num_bits); // Print 5 bits
  55. printf("\n");
  56. printf("Remaining bit_buffer: 0b");
  57. print_binary(bit_buffer, bits_left); // Print remaining bits
  58. printf(", bits_left: %d\n", bits_left);
  59.  
  60. return 0;
  61. }
  62.  
  63.  
  64.  
Success #stdin #stdout 0.01s 5284KB
stdin
123
stdout
Initial bit_buffer: 0b1101011011110010
bit_buffer: 0b1101011011110010
Read 5 bits: 0b11010
Remaining bit_buffer: 0b11011110010, bits_left: 11
bit_buffer: 0b0000011011110010
Read 6 bits: 0b110111
Remaining bit_buffer: 0b10010, bits_left: 5
bit_buffer: 0b0000000000010010
Read 5 bits: 0b10010
Remaining bit_buffer: 0b, bits_left: 0