Possibly lossy conversion from int to byte

I am trying to write hex data to my serial port using java, but now I cannot convert the hex data to a byte array.

Here is the code that shows the error message:

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

      

This is the code writing to 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) {}

      

May I know how to solve this problem. I am currently using the javax.comm plugin. Thank.

+3


source to share


2 answers


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 to indicate the value 0xC6

. The reason for this question is that java is byte

signed, which means its range is -0x80 to 0x7F. You can fix this by saying:



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

      

Or, you can use a negative value within the -0x3A range (which is equivalent to 0x36 in two-digit notation).

+3


source


Try to apply 0xC6

like a range of bytes from -0x80

to 0x7F

:



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

      

0


source







All Articles