Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stddef.h>
- #include <stdint.h>
- // Unsigned Leading Zero Trim (ULZT) is a variable-length quantity algorithm.
- // The first octet advertises the total size and its 'n' bits hold the most
- // significant bits. Any following octets hold the least significant bits in
- // little-endian order.
- //
- // Size Table Including Numeric Range
- //
- // 1 octet: n n n n n n n 0 (0, 127)
- // 2 octets: n n n n n n 0 1 (128, 16'383)
- // 3 octets: n n n n n 0 1 1 (16'384, 2'097'151)
- // 4 octets: n n n n 0 1 1 1 (2'097'152, 268'435'455)
- // 5 octets: n n n 0 1 1 1 1 (268'435'456, 34'359'738'367)
- // 6 octets: n n 0 1 1 1 1 1 (34'359'738'368, 4'398'046'511'103)
- // 7 octets: n 0 1 1 1 1 1 1 (4'398'046'511'104, 562'949'953'421'311)
- // 8 octets: 0 1 1 1 1 1 1 1 (562'949'953'421'312, 72'057'594'037'927'935)
- // 9 octets: 1 1 1 1 1 1 1 1 (72'057'594'037'927'936, 18'446'744'073'709'551'615)
- #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
- #error "need little-endian byte order"
- #endif
- // Encodes up to 9 octets in buf and returns the final position, exclusive.
- void* ulzt64enc(void* buf, uint64_t v) {
- uint8_t* first = (uint8_t*) buf;
- uint8_t* p = first + 1;
- unsigned int n = 0;
- uint_fast8_t mask = 0;
- while (v > 127 >> n++) {
- *p++ = v;
- v >>= 8;
- mask = mask << 1 | 1;
- }
- *first = v << n | mask;
- return p;
- }
- // Decodes up to 9 octets from buf and returns the final position, exclusive.
- // The value of address v must be zero and buflen must be grather than zero.
- // When EOF, the result is undefined.
- void* ulzt64dec(uint64_t* v, void* buf, size_t buflen) {
- uint8_t* p = (uint8_t*) buf;
- uint8_t* vp = (uint8_t*) v;
- uint_fast8_t first = *p++;
- for (; first & 1 && --buflen; first >>= 1)
- *vp++ = *p++;
- if (first) *vp = first >> 1;
- return p;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement