Nav*_*abu 1 java swt operators
这是我看到一段时间的代码.我想知道代码是如何工作的.
public static final int MULTI = 1 << 1;
public static final int SINGLE = 1 << 2;
public static final int READ_ONLY = 1 << 3;
SWT.MULTI | SWT.SINGLE | SWT.READ_ONLY
Run Code Online (Sandbox Code Playgroud)
我深入研究TableViewer(Composite parent, int style)了寻找答案的课程实施,但没有找到太多.
我找到了这段代码,但并不太了解
static int checkBits (int style, int int0, int int1, int int2, int int3, int int4, int int5) {
int mask = int0 | int1 | int2 | int3 | int4 | int5;
if ((style & mask) == 0) style |= int0;
if ((style & int0) != 0) style = (style & ~mask) | int0;
if ((style & int1) != 0) style = (style & ~mask) | int1;
if ((style & int2) != 0) style = (style & ~mask) | int2;
if ((style & int3) != 0) style = (style & ~mask) | int3;
if ((style & int4) != 0) style = (style & ~mask) | int4;
if ((style & int5) != 0) style = (style & ~mask) | int5;
return style;
}
Run Code Online (Sandbox Code Playgroud)
包装在一起
我们来看看这段代码吧.
public static final int MULTI = 1 << 1;
public static final int SINGLE = 1 << 2;
public static final int READ_ONLY = 1 << 3;
Run Code Online (Sandbox Code Playgroud)
"<<"运算符意味着将位移到左侧."<<"运算符后面的数字告诉我们要移位多少位.
所以,另一种编写代码的方法是.
public static final int MULTI = 2;
public static final int SINGLE = 4;
public static final int READ_ONLY = 8;
Run Code Online (Sandbox Code Playgroud)
通过这种方式定义标志,可以将值一起进行"或"("添加")并保存在一个字节或一个整数中.
SWT.MULTI | SWT.SINGLE
Run Code Online (Sandbox Code Playgroud)
这就是将两个值的位组合在一起.但是,这是什么意思?
在这种情况下,由于我们将值定义为单个位,因此它与添加值相同.
MULTI = 2
SINGLE = 4
Run Code Online (Sandbox Code Playgroud)
因此,状态值为6(2 + 4).
现在记住,我们没有添加.因为我们使用的是比特,所以效果与我们添加的效果相同.
打开比特包
你发布的第二段代码基本上是我们提出的6,然后将它拆分为2和4.它的工作原理是每次检查每个位,然后查看它是否存在.
让我们走一条线,看看它在做什么.
if ((style & int1) != 0) style = (style & ~mask) | int1;
Run Code Online (Sandbox Code Playgroud)
int1代表其中一个样式位.为了便于讨论,我们假设它是MULTI,值为2.
第一部分(if条件)测试该位是否在样式整数中设置.
第二部分有点棘手.(比特,得到它.非常麻烦.)
掩码的值在代码中给出.
int mask = int0 | int1 | int2 | int3 | int4 | int5;
Run Code Online (Sandbox Code Playgroud)
这只是OR的所有状态值.从我们最初的MULTI,SINGLE和READ_ONLY示例中,我们给出了一个x'0E'或14的掩码.通过本讨论的其余部分,我将使用十六进制.
状态位存在
现在,回到我们谈论的那条线上.
if ((style & int1) != 0) style = (style & ~mask) | int1;
Run Code Online (Sandbox Code Playgroud)
style & int1是一个AND操作.这意味着该位具有两个被设置style和int1. Style从我们之前设定之前是x'06'(2 + 4). int1是x'02'.当你和'x'06'和x'02'时,你得到x'02',这就是if的值true.
~mask将x'0E'转换为x'F1'.换句话说,所有位都从0翻转为1,从1翻转为0.
style & ~mask是一个AND操作.当你和'x'06'和x'F1'时,你得到x'00'.换句话说,没有一个比特匹配.
我们之前说过,int1是MULTI,值为2或x'02'.现在我们做一个OR操作,我们之前解释过.ORing x'00'和x'02'给出了x'02',这是我们想要提取的MULTI值.
状态位不存在
另一种选择(当状态位不存在时)会导致稍微不同的结果.我们没有设置READ_ONLY,所以让我们进行计算.
READ_ONLY是x'08'.风格是x'06'当你和那些价值观在一起时
if ((style & int1) != 0) style = (style & ~mask) | int1;
Run Code Online (Sandbox Code Playgroud)
你得到x'00',这会导致if的值false.
理由
将几个状态值放入一个字节或单词的最初原因是为了节省内存.40年前,当计算机内存有限时,这很重要.现在,它是为了方便传递状态而做的.您可以传递一个状态指示器,而不是将7或15个不同的状态指示器从一种方法传递到另一种方法
正如您所看到的,权衡是需要一些代码来提取状态位,以便您可以使用它们.