possibly lossy conversion from int to byte

3.5k views Asked by At

I am trying to write hexadecimal data into my serial port using java, but now I cant convert the hexadecimal data into the byte array.

Here is the code which shows the error message:

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

This is the code writing into the serial port:

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) {}

Can I know how can I solve this problem. Currently I am using the javax.comm plugin. Thank you.

2

There are 2 answers

4
nanofarad On BEST ANSWER

If you look at the error message:

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

There is a small caret pointing to the value 0xC6. The reason for the issue is that java's byte is signed, meaning that its range is from -0x80 to 0x7F. You can fix this by casting:

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

Or, you can use the negative, in-range value of -0x3A (which is equivalent to 0x36 in two's-complement notation).

1
Rahul Tripathi On

Try to cast 0xC6 like this as byte range is from -0x80 to 0x7F:

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