开发者

Power of 2 bit operator in Java?

开发者 https://www.devze.com 2023-03-07 12:43 出处:网络
I have a int variable to save the option, that may include none, one or many sub-options like this: public static final int OPERATOR_PLUS = 1;

I have a int variable to save the option, that may include none, one or many sub-options like this:

public static final int OPERATOR_PLUS = 1;
public static final int OPERATOR_SUBTRACT = 2;
public static 开发者_Go百科final int OPERATOR_MULTIPLY = 4;
public static final int OPERATOR_DIVIDE = 8;

And I need a function that will return if that variant contains a sub-option. I tried:

return (Operator & Operators);
return (Operator && Operators);

But Eclipse says both of them are grammar errors (both Operator and Operators are int). Please tell me how to use AND Bit operator in Java. In .NET, I use: Operator And Operators.

Thanks.


Java won't treat an int as a boolean (unlike C++, AFAIU). Try

return (Operator & Operators) > 0;


What is the return type of your method? If it is boolean, then you should write it like this:

public boolean hasOperatorBit() {
    return (Operator & Operators) != 0;
}


The first one is the bitwise AND operator, and should be valid syntax, so long as the return type of your method is int, or something equivalent. If you want a boolean return type, you'll need to do something like return (operator & operators) != 0;.

The second one is not valid; it's a logical AND operator, so both of its arguments need to be boolean.


You need to compare your variable with the operator in question using bitwise AND to see if that is equivalent to the operator.

Eg,

return OPERATOR_PLUS & operators == OPERATOR_PLUS;

Because if you think about how bitwise works, you want to say does my variable contain the bit flag for the operator.


The first line would be correct to check that, whereas you can only check one operator possibility at a time. Furthermore you have to check whether the result is not equal to 0 to be correct.

return ((operator & sub_operator) != 0);


public boolean checkOperator(int operators, int operator) {
 return (operators & operator) != 0;
}

Tutorials for better understanding.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号