从 int 到 byte 的可能有损转换

possibly lossy conversion from int to byte

我正在尝试使用 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 插件。谢谢。

如果您查看错误信息:

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

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

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

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

尝试像这样转换 0xC6,因为字节范围是从 -0x800x7F:

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