I know how bitwise AND works,but I don’t understand how does (sourceDragMask & NSDragOperationGeneric) work here,I don’t get the point.Is there anyone can explain to me?Thanks a lot.
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard;
NSDragOperation sourceDragMask;
sourceDragMask = [sender draggingSourceOperationMask];
pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSColorPboardType] )
{
if (sourceDragMask & NSDragOperationGeneric)
{
return NSDragOperationGeneric;
}
}
return NSDragOperationNone;
}
NSDragOperationGenericis 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
NSDragOperationGenericbit 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 asigned char) variable, you’ll assign zero to the variable! This is why you sometimes see code like this:or this:
or this:
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.