#include <stdint.h>
#include <string.h>
// Little endian encoding
size_t encodeMSBlittleEndian(uint64_t value, uint8_t* out) {
uint8_t *p = out;
while (value > 127) {
*p++ = value | 0x80;
value >>= 7;
}
*p++ = value;
return p - out;
}
// Little endian decoding
size_t decodeMSBlittleEndian(uint64_t *value, uint8_t* in) {
// locate end of int
uint8_t *p = in;
while (*p++ & 0x80);
size_t size = p - in;
//decode int
uint64_t ret = 0;
do {
ret = (ret << 7) | (*--p & 0x7F);
} while (p != in);
*value = ret;
return size;
}
Note that little endian encoding makes encoding fast but requires more work to decode. When encoding the integer once and decoding it many times, big endian encoding should be favored.
// Big endian encoding
size_t encodeMSBbigEndian(uint64_t value, uint8_t* out) {
uint8_t buf[9], *p = buf + 9;
*--p = value & 0x7F;
while (value >>= 7) {
*--p = value | 0x80;
}
size_t size = buf + 9 - p;
memcpy(out, p, size);
return size;
}
// Big endian decoding
size_t decodeMSBbigEndian(uint64_t *value, uint8_t* in) {
uint8_t *p = in;
uint64_t ret = *p & 0x7F;
while (*p & 0x80) {
ret = (ret << 7) | (*++p & 0x7F);
}
*value = ret;
return p - in + 1;
}