krot

VLQ

Sep 23rd, 2020
843
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. void to_seq(uint64_t x, uint8_t *out)
  5. {
  6.     int i, j;
  7.     for (i = 9; i > 0; i--) {
  8.         if (x & 127ULL << i * 7) break;
  9.     }
  10.     for (j = 0; j <= i; j++)
  11.         out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
  12.  
  13.     out[i] ^= 128;
  14. }
  15.  
  16. uint64_t from_seq(uint8_t *in)
  17. {
  18.     uint64_t r = 0;
  19.  
  20.     do {
  21.         r = (r << 7) | (uint64_t)(*in & 127);
  22.     } while (*in++ & 128);
  23.  
  24.     return r;
  25. }
  26.  
  27. int main()
  28. {
  29.     uint8_t s[10];
  30.     uint64_t x[] = { 8192};
  31.  
  32.     int i, j;
  33.     for (j = 0; j < sizeof(x)/8; j++) {
  34.         to_seq(x[j], s);
  35.         printf("seq from %llx: [ ", x[j]);
  36.  
  37.         i = 0;
  38.         do { printf("%02x ", s[i]); } while ((s[i++] & 128));
  39.         printf("] back: %llx\n", from_seq(s));
  40.     }
  41.  
  42.     return 0;
  43. }
RAW Paste Data