Java中2位运算符的幂?
我有一个 int 变量来保存选项,它可能不包含一个或多个子选项,如下所示:
public static final int OPERATOR_PLUS = 1;
public static final int OPERATOR_SUBTRACT = 2;
public static final int OPERATOR_MULTIPLY = 4;
public static final int OPERATOR_DIVIDE = 8;
我需要一个函数,如果该变体包含子选项,它将返回。我尝试过:
return (Operator & Operators);
return (Operator && Operators);
但是Eclipse说它们都是语法错误(Operator和Operators都是int)。请告诉我如何在 Java 中使用 AND 位运算符。在 .NET 中,我使用:运算符和运算符
。
谢谢。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Java 不会将
int
视为boolean
(与 C++、AFAIU 不同)。尝试Java won't treat an
int
as aboolean
(unlike C++, AFAIU). Try你的方法的返回类型是什么?如果是
boolean
,那么你应该这样写:What is the return type of your method? If it is
boolean
, then you should write it like this:第一个是按位 AND 运算符,只要方法的返回类型是 int 或等效类型,就应该是有效的语法。如果您想要布尔返回类型,则需要执行类似
return (operator &operators) != 0;
的操作。第二个无效;它是一个逻辑 AND 运算符,因此它的两个参数都必须是布尔值。
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 likereturn (operator & operators) != 0;
.The second one is not valid; it's a logical AND operator, so both of its arguments need to be
boolean
.您需要使用按位 AND 将变量与相关运算符进行比较,看看它是否等于该运算符。
例如,
返回 OPERATOR_PLUS &运算符 == OPERATOR_PLUS;
因为如果您考虑按位的工作原理,您会想说我的变量是否包含运算符的位标志。
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.
第一行检查是正确的,而您一次只能检查一个运算符的可能性。此外,您还必须检查结果是否不等于 0 才正确。
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.
教程以便更好地理解。
Tutorials for better understanding.