abbood
abbood

Reputation: 23558

How are bitwise operators being used in this code?

I was looking at PSPDFkit sample code and saw this:

NSDictionary *options = @{kPSPDFProcessorAnnotationTypes :
                               @(PSPDFAnnotationTypeNone & ~PSPDFAnnotationTypeLink)
                         };

The constants PSPDFAnnotationTypeNone and PSPDFAnnotationTypeLink are defined below:

// Available keys for options. kPSPDFProcessorAnnotationDict in
// form of pageIndex -> annotations.
// ..
extern NSString *const kPSPDFProcessorAnnotationTypes;

// Annotations defined after the PDF standard.
typedef NS_OPTIONS(NSUInteger, PSPDFAnnotationType) {
    PSPDFAnnotationTypeNone      = 0,
    PSPDFAnnotationTypeLink      = 1 << 1,  // Links and multimedia extensions
    PSPDFAnnotationTypeHighlight = 1 << 2,  // (Highlight, Underline, StrikeOut) - 
    PSPDFAnnotationTypeText      = 1 << 3,  // FreeText
    PSPDFAnnotationTypeInk       = 1 << 4,
    PSPDFAnnotationTypeShape     = 1 << 5,  // Square, Circle
    PSPDFAnnotationTypeLine      = 1 << 6,
    PSPDFAnnotationTypeNote      = 1 << 7,
    PSPDFAnnotationTypeStamp     = 1 << 8,
    PSPDFAnnotationTypeRichMedia = 1 << 10, // Embedded PDF videos
    PSPDFAnnotationTypeScreen    = 1 << 11, // Embedded PDF videos
    PSPDFAnnotationTypeUndefined = 1 << 31, // any annotation whose type not recognized
    PSPDFAnnotationTypeAll       = UINT_MAX
};

I understand that ~ is the bitwise not operator and & the bitwise and operator, but what is the purpose of their application in this code?

NSDictionary *options = @{kPSPDFProcessorAnnotationTypes :
                               @(PSPDFAnnotationTypeNone & ~PSPDFAnnotationTypeLink)
                         };

Based on comments below, the above could have been written simply as

NSDictionary *options = @{kPSPDFProcessorAnnotationTypes :@(PSPDFAnnotationTypeNone)};

Since it is the same as (0 & ~2) => 0. What's the point of adding the & ~PSPDFAnnotationTypeLink part?

Upvotes: 0

Views: 230

Answers (3)

yinkou
yinkou

Reputation: 5766

"~" is the bitwise not-operator.

As "&" the bitwise and.

These are usually used for bitmask (like in your example) or other binary operations (as the name lets suggest). More info on wiki - Operators in C and C++.

They are in no relationship to literals.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882426

It's the bitwise NOT operator (same as many C-based languages), which inverts all bits in the underlying value.

So, for example, the eight bit value 0x57 (binary 0101 0111) becomes 1010 1000 or 0xa8.

See here for a more complete description of the various bitwise operators.

Upvotes: 0

First of all, I don't know obj-c, only C, but I guess the '&' is 'bitwise AND' and the '~' is bitwise NOT.

Upvotes: 0

Related Questions