2016-04-12 118 views
0
bitshifting当

我试图做一些二进制对象位与比较:不兼容的错误类型Java中

private int selectedButtons = 0x00; 

private static final int ABSENCE_BUTTON_SELECTED = 0x01; 
private static final int SICKNESS_BUTTON_SELECTED = 0x02; 
private static final int LATENESS_BUTTON_SELECTED = 0x04; 

这里是比较:

boolean absenceButtonEnabled = selectedButtons & ABSENCE_BUTTON_SELECTED; 

但我得到这个错误:

Error:(167, 56) error: incompatible types 
required: boolean 
found: int 

任何想法?

+2

请考虑* Effective Java 2nd Ed的建议*第32项:“使用EnumSet而不是位域”。 –

回答

4

selectedButtons & ABSENCE_BUTTON_SELECTED是一个整数,因为&binary or操作。

要将其转换为布尔使用:

boolean absenceButtonEnabled = (selectedButtons & ABSENCE_BUTTON_SELECTED) != 0; 
+0

巨大的帮助。有道理(就像其他职位一样,但我相信这是第一次!)。谢谢。 – spogebob92

+0

检查AND与0的值是否正常?我通常将它与我检查的任何标志进行比较。 –

+1

如果位标志不相交(使用不同的位),则可以安全使用'!= 0'。这里是ABSENCE_BUTTON_SELECTED只有一位,因此位标记必须是分离的。如果位标记重叠(即枚举[1,2,3,4 ...]),那么您必须与值本身进行比较。 – Rocki

2

它比较为零:

boolean absenceButtonEnabled = selectedButtons & ABSENCE_BUTTON_SELECTED != 0; 
2

两个int S中的返回类型为int。尝试下面的代码。

boolean absenceButtonEnabled = (selectedButtons & ABSENCE_BUTTON_SELECTED) == ABSENCE_BUTTON_SELECTED