简体   繁体   中英

Operator “&” cannot be applied to byte, int, boolean

Upon my previous question about how to compare if combined bits contain a specific bit I am running into this error.

    int flag1 = 1 << 0;
    int flag4 = 1 << 5;

    int combined = flag1 | flag4;

    if (combined & flag1 == flag1) // <-- Operator & cannot be applied to int, boolean

If I cast the flags to byte the error replaces int with byte .

The compiler sees the binary operator & in your if statement, treats it as logical AND (since it expects an expression that returns a boolean ), and checks the types of the arguments.

It encounters one int argument - combined - and one boolean argument - flag1 == flag1 . Since it expects two boolean arguments (the & operator cannot be applied to an int and a boolean ), it gives an error.

Add parentheses in order for the operators to be evaluated in the desired order :

if ((combined & flag1 ) == flag1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM