A variable-length quantity (also referred to as VLQ or
uintvar) is a way to encode up to a 28 bit integer value using only as many bytes as necessary. This was used in MIDI file format as a way to minimize the size of certain event data.
The way it works is fairly simple. As a big-endian series of bytes, the most significant bit (MSB) of each byte is a
1 to indicate that another VLQ byte follows. The remaining 7 bits of each byte make up the decoded value.
Example (from Wikipedia):
[ 0x86, 0xc3, 0x17 ] => 106903
Additional references: Wikipedia.
Given a variable-length quantity, convert it to it's integer value.
A list of one to four bytes or a 32-bit value type representing a valid VLQ of an integer.
The integer value of the VLQ input.
Rules and scoring:
- This is code-golf, so shortest answer in bytes for each language wins.
- Standard rules and default I/O rules apply.
- Loopholes forbidden (of course).
- Please provide link with a test for your code (TIO.run, etc).
- A clear explanation for your answer is highly recommended.
- Built-ins that handle this conversion are not banned, however not using them is a lot more interesting.
Input (VLQ) Output (int) [ 0x00 ] => 0 [ 0x07 ] => 7 [ 0x7f ] => 127 [ 0x81, 0x00 ] => 128 [ 0xC0, 0x00 ] => 8192 [ 0xff, 0x7f ] => 16383 [ 0x81, 0x80, 0x00 ] => 16384 [ 0x86, 0xc3, 0x17 ] => 106903 [ 0xbd, 0x84, 0x40 ] => 1000000 [ 0xff, 0xff, 0x7f ] => 2097151 [ 0xC0, 0x80, 0x80, 0x00 ] => 134217728 [ 0xFF, 0xFF, 0xFF, 0x7F ] => 268435455
Note: you are not required to use hex literals to represent a byte as your input or output. You may use decimal literal (
[ 129, 128, 0 ]), integer (
0x80818000) or any other reasonable byte/octet representation if better suited to your platform. Format is flexible as long as it represents 1-4 byte/octets.