0

I am working with a device that supports little endian byte order. How do I do this in Java?

I have created a byte stream from the hex data and wrote it to the socket output stream. I am supposed to send data in the following format.

Protocol-Version: 0x0001

Request_Code: 0x0011

Request_Size: 0x00000008

String s = "0001001100000008";
byte[] bytes = hexStringToByteArray(s);
socket.getOutputStream().write(bytes);

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
            + Character.digit(s.charAt(i+1), 16));
    }
    return data;
} 

I am however not receiving any response from the device for this request. Am I doing something wrong?

9
  • If you debug your program on the C-end, what data does it receive for the protocol version, request code, and request size? Commented Feb 5, 2019 at 20:42
  • 1
    Just to be clear: you appear to be sending character data, not numbers in "binary", so the need for "little endian" is not clear. Can you verify what you are supposed to send? Is it ASCII/UTF-8 or do you need to actually send the data as binary words? Commented Feb 5, 2019 at 22:16
  • I am not debugging on the C end. I don't have access to it. Commented Feb 5, 2019 at 22:16
  • You need to debug on the server. Can you set up a test server that duplicates the code from the server? Commented Feb 5, 2019 at 22:17
  • Hey @markspace I'm new to this so i'm not sure. The document says "All data transmitted over the Ipv4-1 communication protocol is in Little Endian (Intel) byte order". I think I have to send the hex data as a byte array in little endian. Commented Feb 5, 2019 at 22:22

1 Answer 1

3

Here's an example using a ByteBuffer. Code is untested so make sure it works for you.

ByteBuffer bb = new ByteBuffer.allocate( 1024 );

short version = 0x0001;
short request = 0x0011;
int size = 0x08;

bb.order( ByteOrder.LITTLE_ENDIAN );
bb.put( version );
bb.put( request );
bb.put( size );

socket.getChannel().write( bb );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.