Search code examples
javaandroidbyte

Imcompatible types: byte cannot be converted to boolean


I have a class with values which I construct as object and send message to main handler. I can work with int without any trouble but some of the values are boolean. This is where I run into the following error in bytes[5] and bytes[6]

byte[] bytes = new byte[259];

message_to_device = new MyDevice(bytes[3], //int
                                 bytes[4], //int
                                 bytes[5], // boolean
                                 bytes[6]  // boolean);
                                        
Message message = Message.obtain();
message.obj = message_to_device;
message.what = MESSAGE;
mhandler.sendMessage(message);

I have come across BitSet, will that be any of use? I am not so familiar with bits and byes in Android yet. How can I proceed?


Solution

  • This can be explicitly casted:

    new MyDevice(
        (int)       bytes[3], // integer value
        (int)       bytes[4], // integer value
        bytes[5] != (byte) 0, // boolean result
        bytes[6] != (byte) 0  // boolean result
    );
    

    But it also works without casting, since in Java one can use byte instead of int:

    new MyDevice(bytes[3], bytes[4], bytes[5] != 0, bytes[6] != 0);
    

    As the definition for byte reads:

    They can also be used in place of int where their limits help to clarify your code;

    the fact that a variable's range is limited can serve as a form of documentation.

    Or add a constructor alike: public MyDevice(byte, byte, byte, byte) or even public MyDevice(byte[]). MyDevice could even have setters, accepting byte values, which set boolean fields. For example:

    class MyDevice {
        // public MyDevice(int arg0, int arg1, boolean arg2, boolean arg3) {}
        public MyDevice(byte arg0, byte arg1, byte arg2, byte arg3) {}
        public MyDevice(byte[] arg0) {}
    }