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

故事扮演 提交于 2019-12-13 03:57:07

问题


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?


回答1:


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 );


来源:https://stackoverflow.com/questions/54542268/sending-a-byte-stream-from-a-java-program-to-a-device-running-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!