I want to pack a MIDI message into an NSData object.
int messageType = 3; // 0-15
int channel = 5; // 0-15
int data1 = 56; // 0-127
int data2 = 78; // 0-127
int packed = data2;
packed += data1 * 127;
packed += channel * 16129; // 127^2
packed += messageType * 258064; // 127^2 * 16
NSLog(@"packed %d", packed);
NSData *packedData = [NSData dataWithBytes:&packed length:sizeof(packed)];
int recovered;
[packedData getBytes:&recovered];
NSLog(@"recovered %d", recovered);
This works wonderfully and while I'm proud of myself, I know that the conversion to bytes is not done correctly: it should be a direct conversion without a lot of addition and multiplication. How can that be done?
Edit: I'm now aware that I can just do this
char theBytes[] = {messageType, channel, data1, data2};
NSData *packedData = [NSData dataWithBytes:&theBytes length:sizeof(theBytes)];
and on the Java side
byte[] byteBuffer = new byte[4]; // Receive buffer
while (in.read(byteBuffer) != -1) {
System.out.println("data2=" + byteBuffer[3]);
}
and it will work, but I'd like the solution to get me an NSData with just 3 bytes.