tags:

views:

92

answers:

2

I'm doing some work with the JavaSound API to send a MIDI System Exclusive (Sysex) message to an external MIDI device (an electronic keyboard). According to the Yamaha manual, the data to send to light up one of the keys is this series of bytes: F0 43 7F 00 00 03 00 41 F7.

According to the JavaDoc on SysexMessage, the correct way to send data for a message is with setMessage(int status, byte[] data, int length). In this case, F0 (or 240 decimal) is the status, and everything else is the data - including the F7 (247 decimal) at the end, which indicates the end of the Sysex message.

The problem is that bytes in Java are limited to the range -128..127, so I can't send F7 in a byte array. But the JavaDoc for SysexMessage seems oblivious to this fact, saying, "If this message contains all the system exclusive data for the message, it should end with the status byte 0xF7."

Any suggestions for how to correctly send that final byte? Am I misinterpreting the JavaDoc for SysexMessage?

+2  A: 

You are thinking about the number F7 the wrong way. While F7 is the equivalent to 247, it is also -9. But whether you interpret F7 to be the number 247 (as an unsigned byte) or to be the number -9 (as a signed byte) it is still the same sequence of bits 11110111, and when that sequence of bits is transmitted over the line to your keyboard, the keyboard may interpret however it likes.

M. Jessup
+1  A: 

For this kind of problem, you can safely cast any integer value less than or equal to 255 (0xFF) to a byte. The reason being, as Jessup stated, they will be represented by the same bit pattern.

int i = 0xF7;
byte b = (byte)i;
matsev
Is casting necessary? "byte b = 0xF7;" is sufficient, I believe.
tafa
It depends. You can write "byte b = 0x7F;", but you will get an error if you attempt to compile "byte b = 0x80;" (possible loss of precision, found: int, required byte).
matsev