Reputation: 699
I'm trying to convert an int
value to a byte array
, but I'm using the byte
for MIDI information (meaning that the 0x00 byte
which is returned when using GetBytes
acts as a separator) which renders my MIDI information useless.
I would like to convert the int
to an array
which leaves out the 0x00 bytes and just contains the bytes which contain actual values. How can I do this?
Upvotes: 0
Views: 988
Reputation: 1062780
Based on the info Ben added, this should do what you require:
static byte[] VlqEncode(int value)
{
uint uvalue = (uint)value;
if (uvalue < 128) return new byte[] { (byte)uvalue }; // simplest case
// calculate length of buffer required
int len = 0;
do {
len++;
uvalue >>= 7;
} while (uvalue != 0);
// encode (this is untested, following the VQL/Midi/protobuf confusion)
uvalue = (uint)value;
byte[] buffer = new byte[len];
for (int offset = len - 1; offset >= 0; offset--)
{
buffer[offset] = (byte)(128 | (uvalue & 127)); // only the last 7 bits
uvalue >>= 7;
}
buffer[len - 1] &= 127;
return buffer;
}
Upvotes: 0
Reputation: 283634
You've completely misunderstood what you need, but luckily you mentioned MIDI. You need to use the multi-byte encoding that MIDI defines, which is somewhat similar to UTF-8 in that less than 8 bits of data are placed into each octet, with the remaining providing information about the number of bits used.
See the description on wikipedia. Pay close attention to the fact that protobuf uses this encoding, you can probably reuse some of Google's code.
Upvotes: 1