Variable Length MIDI Duration Algorithm

140 views Asked by At

I'm trying to compile MIDI files, and I reached an issue with the duration values for track events. I know these values (according to this http://www.ccarh.org/courses/253/handout/vlv/) are variable length quantities where each byte is made up of a continuation bit (0 for no following duration byte and 1 for a following duration byte) and the rest of the number in a 7 bit representation.

For example, 128 would be represented as such:

1_0000001 0_0000000

The problem is that I'm having trouble wrapping my head around this concept, and am struggling to come up with an algorithm that can convert a decimal number to this format. I would appreciate it if someone could help me with this. Thanks in advance.

1

There are 1 answers

3
EddieLotter On

The official MIDI file format specification has example code for dealing with variable length values. You can freely download the specs from the official MIDI.org website.

Here is the sample code that they provide on page 11:

doubleword ReadVarLen () 
{ 
    register doubleword value; 
    register byte c; 
 
    if ((value = getc(infile)) & 0x80) 
    {
        value &= 0x7f; 
        do
        { 
            value = (value << 7) + ((c = getc(infile)) & 0x7f); 
        } while (c & 0x80); 
    }
    return (value); 
}