0

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.

FireTheLost
  • 131
  • 7
  • Does this answer your question? [Decode MIDI variable length field](https://stackoverflow.com/questions/24711585/decode-midi-variable-length-field) – Paul Dempsey Feb 20 '23 at 20:22
  • I ultimately ended up using this to help me: [Encoding variable-length quanties for MIDI](https://codereview.stackexchange.com/questions/88604/encoding-variable-length-quanties-for-midi) – FireTheLost Feb 22 '23 at 14:57

1 Answers1

0

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); 
} 
Paul Dempsey
  • 639
  • 3
  • 19
EddieLotter
  • 324
  • 3
  • 8
  • Could you, perhaps, guide me to where I could find it? Searches such as ```variable length values midi spec``` or other similar queries don't result in anything useful. – FireTheLost Oct 27 '22 at 07:25
  • Download "MIDI 1.0 Detailed Specification" in the specs section and search for "variable-length numbers" it's all there. – EddieLotter Oct 27 '22 at 14:13
  • It's not in the MIDI spec, which describes on-the-wire MIDI. It's in the MIDI File Format spec (RP-001_v1-0_Standard_MIDI_Files_Specification_96-1-4.pdf). The description is on page #2, the example quoted is on page 11.. – Paul Dempsey Feb 24 '23 at 23:57