3

我正在尝试使用 java 将十六进制数据写入我的串行端口,但现在我无法将十六进制数据转换为字节数组。

这是显示错误消息的代码:

static byte[] bytearray = {0x02, 0x08, 0x16, 0x0, 0x00, 0x33, 0xC6, 0x1B};

这是写入串口的代码:

try {
        outputStream = serialPort.getOutputStream();
        // Write the stream of data conforming to PC to reader protocol
        outputStream.write(bytearray);
        outputStream.flush();

        System.out.println("The following bytes are being written");
        for(int i=0; i<bytearray.length; i++){
            System.out.println(bytearray[i]);
            System.out.println("Tag will be read when its in the field of the reader");
        }
} catch (IOException e) {}

我能知道我该如何解决这个问题。目前我正在使用 javax.comm 插件。谢谢你。

4

2 回答 2

3

如果您查看错误消息:

Main.java:10: error: incompatible types: possible lossy conversion from int to byte
    static byte[] bytearray = {0x02, 0x08, 0x16, 0x0, 0x00, 0x33, 0xC6, 0x1B};
                                                                  ^

有一个小插入符号指向 value 0xC6。问题的原因是 javabyte是有符号的,这意味着它的范围是从 -0x80 到 0x7F。您可以通过强制转换来解决此问题:

    static byte[] bytearray = {0x02, 0x08, 0x16, 0x0, 0x00, 0x33, (byte) 0xC6, 0x1B};

或者,您可以使用负的范围内值 -0x3A(相当于二进制补码表示法中的 0x36)。

于 2015-06-22T16:20:53.857 回答
0

尝试0xC6像这样投射,因为字节范围是从-0x800x7F

static byte[] bytearray = {0x02, 0x08, 0x16, 0x0, 0x00, 0x33, (byte) 0xC6, 0x1B};
于 2015-06-22T16:21:44.230 回答