Sending a byte stream from a java program to a device running C

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?

java
endianness
asked on Stack Overflow Feb 5, 2019 by Sagar Nair • edited Feb 5, 2019 by Jacob G.

1 Answer

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 );
answered on Stack Overflow Feb 5, 2019 by markspace

User contributions licensed under CC BY-SA 3.0