Search code examples
arraysalgorithmbinarypacking

Who remember the algorithm to pack 4-bytes integer to array of 1-to-4 bytes depending from number of significant digits?


I need an efficient algorithm or idea to pack 4-bytes integers to as short as possible byte arrays. For example, I can pack values from 0x00000000 to 0x0000007f to the one-byte array, just assuming that the bit7=0 means 1-byte length. If I have the number from 128 and longer, I need to invent smarter things to pack to 2-bytes array, 3-bytes array, etc.

Who remembers this algorithm? Please share.


Solution

  • Variable Length Quantity: https://en.wikipedia.org/wiki/Variable-length_quantity

    It's also used by UTF-8.