Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possibly lossy conversion from int to byte

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.

like image 211
raaj5671 Avatar asked Oct 17 '25 19:10

raaj5671


1 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 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).

like image 168
nanofarad Avatar answered Oct 20 '25 08:10

nanofarad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!