You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中变量赋值时&位运算符的作用及场景解析

Understanding the Bitwise AND (&) in Your Java/Android Code

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() returns 0x0101 (which is ACTION_DOWN | (1 << 8), meaning pointer 1 triggered a down event)
  • ACTION_MASK is 0xFF (binary 11111111)
  • 0x0101 & 0xFF = 0x01, which is exactly ACTION_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:48:06