Java中变量赋值时&位运算符的作用及场景解析
Hey there! Let's break down what's going on with that & operator you're seeing—it's not the same as combining values like addition, which is where your confusion about 5 & 1 came from.
First, let's clear up that test case: int x = 5 & 1; does not equal 6. It equals 1. Here's why:
- The
&here is the bitwise AND operator, not the logical AND (&&), and it works directly on the binary representation of numbers. - Convert 5 to binary:
101 - Convert 1 to binary:
001 - Bitwise AND compares each corresponding bit: if both bits are 1, the result bit is 1; otherwise, it's 0.
- So
101 & 001 = 001, which translates back to 1 in decimal.
Now, let's look at the Android code you found:
int action = event.getAction() & MotionEvent.ACTION_MASK;
MotionEvent.ACTION_MASK is a constant designed as a bitmask—it's a number where specific bits are set to 1 (usually the lower 8 bits, represented as 0xFF).
Motion events in Android can carry extra information (like the ID of a touch pointer in multi-touch scenarios) by setting higher bits in the action value. For example, an action might be ACTION_POINTER_DOWN | (pointerId << 8). The mask ACTION_MASK filters out those extra bits, leaving only the core action type (like ACTION_DOWN, ACTION_MOVE, etc.).
Think of it like this: if you have a value that's a combination of a main action and extra flags, the bitwise AND with the mask "cuts off" the extra parts, so you only get the part you care about.
To put it in concrete terms:
- Suppose
event.getAction()returns0x0101(which isACTION_DOWN | (1 << 8), meaning pointer 1 triggered a down event) ACTION_MASKis0xFF(binary11111111)0x0101 & 0xFF = 0x01, which is exactlyACTION_DOWN—the pure action type we need.
That's why this pattern is used in Android touch handling: it lets you separate the base action from any additional metadata stored in the same integer.
内容的提问来源于stack exchange,提问作者Neglected Sanity

