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

判断指定位置比特位是否置位:左移掩码与右移数字方案对比及位位置索引规范咨询

Great question! Let’s break this down into two key parts: performance differences between your two methods, and the correct way to index bit positions.

Performance: Left-Shift Mask vs Right-Shift Number

First off, both of your implementations run in O(1) time—they’re single, simple bitwise operations that execute in a single CPU cycle on most modern hardware. So in terms of raw performance, they’re effectively equivalent for valid bit positions (0 to 31 for Java int types).

That said, there’s a subtle edge case to note if you pass a pos value outside the valid range of the integer type:

  • For the left-shift mask approach (1 << pos), Java’s shift operators take the shift amount modulo the size of the type (32 for int). So 1 << 32 is equivalent to 1 << 0 (which is 1), which would incorrectly check the 0th bit instead of signaling an invalid position.
  • For the right-shift number approach (num >> pos), the same modulo rule applies: num >> 32 is equivalent to num >> 0 (the original number), so (num >> 32) & 1 also checks the 0th bit in this edge case.

But for all practical purposes where you’re passing a valid pos (0 ≤ pos ≤ 31), both methods work identically and perform the same. There’s no meaningful advantage of one over the other—use whichever reads more intuitively to you!

Bit Position Indexing: 0-Based or 1-Based?

The industry standard for bit position indexing is 0-based, directly tied to the power-of-2 weight of the bit. Here’s why:

  • The rightmost (least significant) bit has a weight of 2^0 (which is 1), so this is the 0th position.
  • Moving left, each bit’s weight doubles: the next bit is 2^1 (2), which is the 1st position, then 2^2 (4) for the 2nd position, and so on.

Let’s use your example of the number 2 (binary 10):

  • The set bit corresponds to 2^1 (since 2 = 2^1). So to check this bit, you’d pass pos = 1 to either of your methods, which would correctly return true.
  • If you used a 1-based index here (passing pos = 2), you’d be checking the bit with weight 2^2 (4), which isn’t set in 2—so the method would return false, which is incorrect.

Another example: number 5 is binary 101. The 0th bit (weight 1) is set, the 1st bit (weight 2) is not, and the 2nd bit (weight 4) is set. So leftShiftingMask(5, 0) and rightShiftingNumber(5, 0) both return true, while leftShiftingMask(5, 1) returns false.

Always use 0-based indexing for bit positions to align with the mathematical weight of each bit and avoid off-by-one errors.

内容的提问来源于stack exchange,提问作者Akshaya Amar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:57:51