Distributed Information System (DIS)
  • Home
  • The blog
  • Contact

C source code for MSB encoding and decoding

11/2/2015

1 Comment

 
For a detailed explanation see Efficiently encoding variable-length integers in C/C++.

#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;
}
1 Comment

    Author

    Christophe Meessen is a  computer science engineer working in France.

    Any suggestions to make DIS more useful ? Tell me by using the contact page.

    Categories

    All
    Business Model
    Database
    Dis
    Ditp
    Dvcs
    Git
    Gob
    Idr
    Misc
    Murphys Law
    Programming Language
    Progress Status
    Startup
    Suggested Reading
    Web Site

    Archives

    December 2017
    November 2015
    September 2015
    February 2013
    December 2012
    November 2012
    May 2012
    February 2012
    March 2010
    October 2009
    September 2009
    July 2009
    June 2009
    May 2009
    February 2009
    January 2009
    November 2008
    September 2008
    August 2008
    July 2008
    May 2008
    April 2008
    March 2008
    February 2008
    January 2008
    December 2007
    October 2007
    August 2007
    July 2007
    June 2007
    May 2007

    RSS Feed

    Live traffic feed
    You have no departures or arrivals yet. Wait a few minutes and check again.
    Powered by FEEDJIT
Powered by Create your own unique website with customizable templates.