fork download
  1. #include <ios>
  2. #include <cmath>
  3. #include <bitset>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <cstdlib>
  7. #include <iostream>
  8.  
  9. using namespace std;
  10.  
  11. typedef unsigned char byte;
  12. typedef struct bit_data {
  13. byte *data;
  14. size_t length;
  15. } bit_data;
  16.  
  17. /*
  18.   Asume skip_n_bits will be 0 >= skip_n_bits <= 8
  19. */
  20. bit_data *read(size_t n_bits, size_t skip_n_bits) {
  21. bit_data *bits = (bit_data *) malloc(sizeof(struct bit_data));
  22.  
  23. size_t bytes_to_read = ceil(n_bits / 8.0);
  24. size_t bytes_to_read_with_skip = ceil(n_bits / 8.0) + ceil(skip_n_bits / 8.0);
  25.  
  26. bits->data = (byte *) calloc(1, bytes_to_read);
  27. bits->length = n_bits;
  28.  
  29. /* Hardcoded for the sake of this example*/
  30. byte *tmp = (byte *) malloc(3);
  31. tmp[0] = 'A'; tmp[1] = 'B'; tmp[2] = 'C';
  32.  
  33. /*not working*/
  34. if(skip_n_bits > 0){
  35. unsigned char *tmp2 = (unsigned char *) calloc(1, bytes_to_read_with_skip);
  36. size_t i;
  37.  
  38. for(i = bytes_to_read_with_skip - 1; i > 0; i--) {
  39. tmp2[i] = tmp[i] << skip_n_bits;
  40. tmp2[i - 1] = (tmp[i - 1] << skip_n_bits) | (tmp[i] >> (8 - skip_n_bits));
  41. }
  42.  
  43. memcpy(bits->data, tmp2, bytes_to_read);
  44. free(tmp2);
  45. }else{
  46. memcpy(bits->data, tmp, bytes_to_read);
  47. }
  48. free(tmp);
  49.  
  50. return bits;
  51. }
  52.  
  53. int main(void) {
  54. //Reading "ABC"
  55. //01000001 01000010 01000011
  56. bit_data *res = read(8, 4);
  57.  
  58. cout << bitset<8>(*res->data);
  59. cout << " -> Should be '00010100'";
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
00010100 -> Should be '00010100'