stramin
stramin

Reputation: 2390

How to operate bitwise? (Operator & cannot be applied to Integer or int)

I want to check some permissions on an android app, I got these permissions from an API I use for different devices and coding languages, but this is my first attempt on JAVA (Android), and seems it is different.

In my App these permissions are in a class which returns them as an Integer, so if I want to check if the user can delete (decimal 4) I want to do something like this:

if(MyClass.getBit()&4){ // Is bit 2 on?
    // Yes, is on
}

I got the following error:

Required Boolean, Found Int.

That's ok, I can made it boolean:

if(MyClass.getBit()&4 != 0){ // Is bit&4 not 0?
    // Yes, it is different
}

I get a new error:

Operator '&' cannot be applied to 'java.lang.Integer', 'boolean'

So I changed the returned value to int, I got the same:

Operator '&' cannot be applied to 'int', 'boolean'

Seems like I am not going on the correct way...

How to operate bitwises on Android?

Upvotes: 0

Views: 360

Answers (1)

Francesc
Francesc

Reputation: 29260

It's a precedence issue, you have to add parentheses,

if ((MyClass.getBit()&4) != 0){ // Is bit&4 not 0?
    // Yes, it is different
}

Without parentheses, it would perform the (4 != 0) part first, which returns a boolean, then do the AND operator on that boolean and the integer on the left.

Upvotes: 3

Related Questions