VonC posted a good answer about bitmasks in general. Here's some information that's more specific to the code you posted.
Given an integer representing a bit, we work out which member of the array holds that bit. That is: Bits 0 to 31 live in a[0]
, bits 32 to 63 live in a[1]
, etc. All that i>>SHIFT
does is i / 32
. This works out which member of a
the bit lives in. With an optimising compiler, these are probably equivalent.
Obviously, now we've found out which member of a
that bitflag lives in, we need to ensure that we set the correct bit in that integer. This is what 1 << i
does. However, we need to ensure that we don't try to access the 33rd bit in a 32-bit integer, so the shift operation is constrained by using 1 << (i & 0x1F)
. The magic here is that 0x1F
is 31, so we'll never left-shift the bit represented by i
more than 31 places (otherwise it should have gone in the next member of a
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…