[Code] Interesting Bitmask

September 25, 2016

There is a lot of type checking ways. You can define as constant strings to check later on, or you could use enum for convenient way (this one could be used the most) … but there is one way of type checking, that’s is using Bitmask. This article will lead you digging into how to use bitmask in Objective C.

As we easily can see, Apple uses a lot of bitmask in the SDKs, for example: UIViewAutoresizing, UIInterfaceOrientation

We will make our own example, let’s see:

typedef NS_OPTIONS(NSUInteger, PLandayEngineerTeam) {
    PLandayEngineerTeam_Mobile        = 1 << 0,
    PLandayEngineerTeam_Backend       = 1 << 1, 
    PLandayEngineerTeam_Frontedn      = 1 << 2 
};

We actually used Bitwise operator, called Bit shift in this case, because in this operation, the digits are moved, or shifted. With our example, the digits are moved to left. For more info you could check this out, talking about Bitwise operations: https://en.wikipedia.org/wiki/Bitwise_operation

So now we present the example in Binary:

typedef NS_OPTIONS(NSUInteger, PLandayEngineerTeam) {
    PLandayEngineerTeam_Mobile        = (1 << 0), // => 00000001
    PLandayEngineerTeam_Backend       = (1 << 1), // => 00000010
    PLandayEngineerTeam_Frontedn      = (1 << 2)  // => 00000100
};

Got it?

HOW TO USE?

1. Use | (Bitwise OR) for setting on or turning on a flag.

For example:

    PLandayEngineerTeam teams = PLandayEngineerTeam_Mobile | PLandayEngineerTeam_Backend;

    Actually:
        00000001
    | 
        00000010
        ========
        00000011

If you want to add more flag in existing flags:

teams |= PLandayEngineerTeam_Frontend;

2. Use & (Bitwise AND) for checking the state of a flag.

    if (teams & PLandayEngineerTeam_Mobile == PLandayEngineerTeam_Mobile) {
        // is Mobile Team.
    }

It is explained as:

        00000011 
    & 
        00000001
        ========
        00000001  // PLandayEngineerTeam_Mobile

Two both bitwise operators are good for normally work, but there is further more. Let’s continue.

3. Use ~ (Bitwise NOT) for Deleting a flag.

teams &= ~PLandayEngineerTeam_Backend;

Actually:

~PLandayEngineerTeam_Backend // ~00000010 == 11111101

        00000011
    &
        11111101
        ========
        00000001 // == PLandayEngineerTeam_Mobile

4. Use ^ (Bitwise XOR) for toggling a flag (turns it on if it was off, or off if it was on), rarely used.

For example:

teams ^= PLandayEngineerTeam_Backend;

Why using it?

Conclusion

Well, so like them or not, in my opinion, these are used a lot by Apple, so it would be benefit if we’re familiar with them. And one more thing, life will be excited to know things.

Happy coding.

References: * http://www.vipan.com/htdocs/bitwisehelp.html * https://www.bignerdranch.com/blog/smooth-bitwise-operator/ * http://nshipster.com/ns_enum-ns_options/