I know how bitwise AND works,but I don't understand how does (sourceDragMask & NSDragOperationGeneric) work here,I don't get the point.
NSDragOperationGeneric
is most likely a power of two, which means it has only one bit set. This is deliberate: Bit masks are almost all defined as powers of two (single bits) to enable bit-mask operations like this one.
The bitwise-AND operation, as you know, evaluates to only those bits that are set in both sides. If one side has only one bit (NSDragOperationGeneric
) set, then the operation effectively tests whether that bit is set in the other side.
That's the point of the operation: To test whether the NSDragOperationGeneric
bit is set.
There is one gotcha: As you know, a successful bitwise AND test will evaluate to the tested-for bit mask, not 1. So, for example, if you test for a bit mask that's defined as 0x100 (1 followed by 8 clear bits), then assign that result to a BOOL
(which is a signed char
) variable, you'll assign zero to the variable! This is why you sometimes see code like this:
BOOL supportsCopyOperation = ((dragOperations & NSDragOperationCopy) == NSDragOperationCopy);
or this:
BOOL supportsCopyOperation = ((dragOperations & NSDragOperationCopy) != 0);
or this:
BOOL supportsCopyOperation = !!(dragOperations & NSDragOperationCopy);
Other bit-mask operations include bitwise-OR (|
) to set bits in a value (return NSDragOperationCopy | NSDragOperationMove;
, for example) and bitwise-NOT (~
, a.k.a. two's complement) to invert the bits of a value, usually for “anything but” tests.