Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <stdint.h>
  3.  
  4. // Unsigned Leading Zero Trim (ULZT) is a variable-length quantity algorithm.
  5. // The first octet advertises the total size and its 'n' bits hold the most
  6. // significant bits. Any following octets hold the least significant bits in
  7. // little-endian order.
  8. //
  9. // Size Table Including Numeric Range
  10. //
  11. // 1 octet: n n n n n n n 0 (0, 127)
  12. // 2 octets: n n n n n n 0 1 (128, 16'383)
  13. // 3 octets: n n n n n 0 1 1 (16'384, 2'097'151)
  14. // 4 octets: n n n n 0 1 1 1 (2'097'152, 268'435'455)
  15. // 5 octets: n n n 0 1 1 1 1 (268'435'456, 34'359'738'367)
  16. // 6 octets: n n 0 1 1 1 1 1 (34'359'738'368, 4'398'046'511'103)
  17. // 7 octets: n 0 1 1 1 1 1 1 (4'398'046'511'104, 562'949'953'421'311)
  18. // 8 octets: 0 1 1 1 1 1 1 1 (562'949'953'421'312, 72'057'594'037'927'935)
  19. // 9 octets: 1 1 1 1 1 1 1 1 (72'057'594'037'927'936, 18'446'744'073'709'551'615)
  20.  
  21.  
  22. #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
  23. #error "need little-endian byte order"
  24. #endif
  25.  
  26. // Encodes up to 9 octets in buf and returns the final position, exclusive.
  27. void* ulzt64enc(void* buf, uint64_t v) {
  28. uint8_t* first = (uint8_t*) buf;
  29. uint8_t* p = first + 1;
  30.  
  31. unsigned int n = 0;
  32. uint_fast8_t mask = 0;
  33. while (v > 127 >> n++) {
  34. *p++ = v;
  35. v >>= 8;
  36. mask = mask << 1 | 1;
  37. }
  38. *first = v << n | mask;
  39.  
  40. return p;
  41. }
  42.  
  43. // Decodes up to 9 octets from buf and returns the final position, exclusive.
  44. // The value of address v must be zero and buflen must be grather than zero.
  45. // When EOF, the result is undefined.
  46. void* ulzt64dec(uint64_t* v, void* buf, size_t buflen) {
  47. uint8_t* p = (uint8_t*) buf;
  48. uint8_t* vp = (uint8_t*) v;
  49.  
  50. uint_fast8_t first = *p++;
  51. for (; first & 1 && --buflen; first >>= 1)
  52. *vp++ = *p++;
  53. if (first) *vp = first >> 1;
  54.  
  55. return p;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement