从Java程序向运行C的设备发送字节流 [英] Sending a byte stream from a java program to a device running C

查看:88
本文介绍了从Java程序向运行C的设备发送字节流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用支持小尾数字节顺序的设备。

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.


协议版本:0x0001

Protocol-Version: 0x0001

Request_Code:0x0011

Request_Code: 0x0011

Request_Size:0x00000008

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?

推荐答案

下面是一个使用ByteBuffer的示例。代码未经测试,因此请确保它对您有用。

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

这篇关于从Java程序向运行C的设备发送字节流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆