C# – Midi Variable Length Quantity
On the way home on the train for Christmas, I began porting my Midi parsing class over to C#.
The snippet below shows how to read to read a Variable Length Quantity (sometimes known as a Variable Length Value).
The way it works is very simple, it checks the first byte to see if the MSB is set, if it set it will keep iterating, moving along one byte and doing the same, shifting the previous value across 7 bits until the MSB isn’t set.
If it isn’t set on the initial test, the value from that byte will be used for the value of the VLQ.
//
//
using System;
//
//
namespace Midi
{
class VariableLengthQuantity
{
//
// Functions
public VariableLengthQuantity( byte[] inVariableData, int inOffset )
{
int offset = inOffset;
// At least one byte is always used
m_value = inVariableData[offset];
m_numBytes = 1;
++offset;
//
if( ((m_value & 0x80) != 0) )
{
UInt32 c;
//
m_value &= 0x7F;
//
do
{
//
c = inVariableData[offset];
//
m_value = (m_value << 7) + (c & 0x7F);
//
++m_numBytes;
++offset;
} while( (c & 0x80) != 0 );
}
}
//
//
public UInt32 Value
{
get
{
return m_value;
}
}
//
//
public UInt32 NumBytes
{
get
{
return m_numBytes;
}
}
//
// Attributes
UInt32 m_value;
UInt32 m_numBytes;
}
}
No Comments »
RSS feed for comments on this post. TrackBack URL
Leave a comment
You must be logged in to post a comment.