0

I'm writing Java code with usb4java for communication with a measurement instrument connected through USB using control transfers (Windows). The data is transferred using a ByteBuffer populated with hexadecimal values expected by the device.

Here's the relevant fragment of code:

byte[] query = new byte[]{ 0x1d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
ByteBuffer buffer = ByteBuffer.allocateDirect(8);
buffer.put(query);
buffer.rewind();
int transferred = LibUsb.controlTransfer(handle, (byte)0x21, (byte)0x1, (short)0, (short)0, buffer, 1000);

The code works fine, but whenever any value in the buffer is over 0x7F (127), an incorrect number is passed and the device doesn't respond properly.

I'm clearly hitting the limit of the signed byte type used in Java. But is there a way to get around it and get the correct value to the device?

These have been really tough few days and just as the problem appeared to be solved, I hit the wall with the byte size limit. Thanks in advance for any suggestions!

Sasha
  • 93
  • 9

2 Answers2

0

Try putting -1 in the array, since that should be represented as 11111111 when you are using a signed 8-bit type. You could probably write it as 0xFF - 256 to make your intention clear.

If that doesn't work, could you elaborate on what you mean by "an incorrect number is passed"?

David Grayson
  • 84,103
  • 24
  • 152
  • 189
0

Not sure if I understand you right but the following should work correctly:

byte[] query = new byte[]{ (byte)0xFF, (byte)0xFE, 0x7F, 0x50, 0x0, 0x0, 0x0, 0x0 };
ByteBuffer buffer = ByteBuffer.wrap(query);

As you can see, you have to explicitly cast values above 0x7F to byte but that won't change the bit pattern. The value will just get truncated to 8 bits. Another example:

byte b = (byte) 0xFF; // 0b11111111
b++; // 0b0 after increment

Since the value 0xFF is explicitly casted to byte, it becomes 0x00 after the increment, as expected.

reflective_mind
  • 1,475
  • 3
  • 15
  • 28