1

I'm parsing a byte array which contains variables of different types. I'm getting this array from HID connected to my phone. Array was made by C programmer. I'm trying to parse it using ByteBuffer class:

byte[] buffer = new byte[64];
if(connection.bulkTransfer(endpoint, buffer, 64, 1000) >= 0)
{
    ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
    char mId = byteBuffer.getChar();
    short rId = byteBuffer.getShort();
    // ............................
}

But the values of this variables are not correct. Can anyone please tell me what i'm doing wrong?

1
  • I assume connection means you're getting it over a network? How about little- versus big-endianness, i.e., byte ordering.
    – Zhe
    Aug 9, 2013 at 16:43

2 Answers 2

4

There are systems with LitteEndian Byte order and BigEndian.

java uses BigEndian.

If the c programmer wrote the byte array in Little endian, you could use DataInputStream based on an Appache LittleEndianInputStream:

LittleEndianInputStream leis = new LittleEndianInputStream(is);
DataInputStream dis = new DataInputStream(leis);

int i1 = dis.readInt();
short s2 = dis.readShort();

If you and your colleague define a binary interface (file, or byte array) you always should force a speciifc byte order (Either little or big endian).

3

If byte order (little vs big endian) is the issue, you can set the byte order for the ByteBuffer to native without changing all of the program:

ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.nativeOrder()); // Set native byte order
char mId = byteBuffer.getChar();
short rId = byteBuffer.getShort();

On the other hand, if you find ByteBuffer objects more convenient than byte arrays, tell the C programmer to return you a direct byte buffer instead of an array: easier for all parties and probably more efficient.

7
  • Some variables have type unsigned char or unsigned short. Is it correct to use methods getShort() or getChar() for them?
    – floyd
    Aug 9, 2013 at 17:33
  • It's correct, the bits are the same. The sign affects only how the value is displayed or converted into wider types.
    – Joni
    Aug 9, 2013 at 17:35
  • Now my issue is that there is only 1 byte for each char variable in byte buffer. So i can't use getChar() method because it makes char from 2 bytes. I'm trying to cast byte to char: char c = (char) (byteBuffer.get() << 8); But i'm still getting incorrect values of this char variables.
    – floyd
    Aug 10, 2013 at 9:48
  • True, a char in C is a byte in Java. The part of the buffer that contains chars, does it stand for text? What is the character encoding?
    – Joni
    Aug 10, 2013 at 9:53
  • No, it stands for numbers. 1 byte - 1 unsigned char variable.
    – floyd
    Aug 10, 2013 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.