旧C风格游戏源码中,为何采用位移位操作定义宏?
(1<<n) for Bitmask Macros Instead of Hex Values? Great question—this is a super common pattern in C/C++ code, especially for bitmask flags, and there are several practical reasons to prefer (1<<n) over hardcoding hex values like 0x01:
Readability at a glance
When you see(1<<0), you immediately know this is the 0th bit being set. Compare that to0x01—you have to stop and think "wait, which bit is that?" For higher bits, this difference becomes even bigger:(1<<15)is obviously the 15th bit, while0x8000requires mental math to map it to a bit position. It makes the code's intent way clearer.Easier maintenance
If you ever need to move a flag to a different bit position, you just change the number in the shift—no need to recalculate the hex value. For example, switching from(1<<0)to(1<<3)is trivial, whereas changing0x01to0x08requires computing the new hex value (and it's easy to make mistakes with higher bits like(1<<23)vs0x800000).Explicit intent
Writing(1<<n)screams "this is a bitmask for bitwise operations" to other developers. A raw hex value like0x02could be just a regular integer, but the shift syntax makes it obvious this value is meant to be used with|,&, or^for flag manipulation.Cross-platform clarity
While modern systems mostly use 32/64-bit integers, the shift syntax avoids ambiguity about which bit you're targeting. For example,0x8000might be the highest bit in a 16-bit int or the 15th bit in a 32-bit int—but(1<<15)explicitly refers to the 15th bit regardless of the integer size (as long as the type can hold it).
And to clear up your confusion: the preprocessor evaluates (1<<0) at compile time, so it's treated exactly like the literal 1 in the final code. There's no "shift object"—it's just a way to write the value in a more meaningful way for bitmask use cases.
Edit: Thanks everyone for the helpful explanations!
内容的提问来源于stack exchange,提问作者Cosmic M93

