什么时候应该使用这种int变量? [英] When should I use this kind of int variables?

查看:59
本文介绍了什么时候应该使用这种int变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.awt.Event 类中的一些int变量按位设置.如下所示:

Some int variables in java.awt.Event class is set by bitwise. Like below:

/**
 * This flag indicates that the Shift key was down when the event
 * occurred.
 */
public static final int SHIFT_MASK      = 1 << 0;

/**
 * This flag indicates that the Control key was down when the event
 * occurred.
 */
public static final int CTRL_MASK       = 1 << 1;

/**
 * This flag indicates that the Meta key was down when the event
 * occurred. For mouse events, this flag indicates that the right
 * button was pressed or released.
 */
public static final int META_MASK       = 1 << 2;

/**
 * This flag indicates that the Alt key was down when
 * the event occurred. For mouse events, this flag indicates that the
 * middle mouse button was pressed or released.
 */
public static final int ALT_MASK        = 1 << 3;

为什么不直接使用加1的整数直接编码.

Why not coding directly using integers incremented by 1.

public static final int SHIFT_MASK = 1;

public static final int CTRL_MASK = 2;

public static final int META_MASK = 3;

public static final int ALT_MASK = 4;

是否有历史原因或仅仅是程序员的编码习惯?

Is there any historical reason or it's just programmer's coding habit?

也许您可以使用 a&b 比较两个变量,但 a == b 也可以.

Maybe you can use a & b to compare two variables but a == b works too.

是否适合某些情况?如果可以,请给我一个例子吗?

Does it suit for some situations?If so , could you please give me an example?

希望得到您的答复,谢谢.

Hope to get answer from you, thanks.

推荐答案

如果以二进制形式查看,则更有意义:

If you look at its binary form, it makes more sense:

1 << 0 :  00000001
1 << 1 :  00000010
1 << 2 :  00000100
1 << 3 :  00001000

这种位图通常允许您同时传递多个值(作为某种修饰符).

Such kind of bit map usually allow you to pass more than 1 value at the same time (as some kind of modifier).

因此,您可能会看到类似的内容:

Therefore, you may see something like:

// modifiers is a single int
if ((modifiers & SHIFT_MASK) != 0) {
    // shift pressed
}
if ((modifiers & CTRL_MASK) != 0) {
    // ctrl pressed
}....

(如果将它们定义为1,2,3,4,则无法执行此操作

(which you cannot do if you defined them as 1,2,3,4)

您可以认为它正在传递一组位.这样的掩码可以确定特定位是否为"ON",或在不影响其他位的情况下打开/关闭特定位

You can think of it being passing a set of bits. Such mask to determine whether a specific bit is "ON", or to turn on/off a specific bit without affecting other bits

这篇关于什么时候应该使用这种int变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆