1

I am learning Objective-c and I can't understand what are BitMasks, can anyone help me to understand it please? And I also don't know what is the function of this operator << is.

S.Spieker
  • 7,005
  • 8
  • 44
  • 50
Omar
  • 11
  • 2
  • 1
    This is not spacific to Objective-C, you could find information on Google Or Wikipedia (https://en.wikipedia.org/wiki/Mask_(computing)) as for the Shift Operator (<<, >>) you can all so find information in Google http://www.cprogramming.com/tutorial/bitwise_operators.html – hoss Jun 14 '15 at 19:58
  • This is likely a duplicate... – nhgrif Jun 15 '15 at 00:25
  • possible duplicate of [What are bitwise operators?](http://stackoverflow.com/questions/276706/what-are-bitwise-operators) – mario Jun 15 '15 at 09:56

1 Answers1

1

Objective C is an existing of C, and it uses the same bitwise operators. Lets take UIRemoteNotificationType as an example:

UIRemoteNotificationTypeNone    = 0,
UIRemoteNotificationTypeBadge   = 1 << 0,
UIRemoteNotificationTypeSound   = 1 << 1,
UIRemoteNotificationTypeAlert   = 1 << 2,
UIRemoteNotificationTypeNewsstandContentAvailability = 1 << 3,

The << is the shift left operator and its function is obvious once you look at the binary form:

1 << 0 = 1 (decimal) = 0000001 (binary)
1 << 1 = 2 (decimal) = 0000010 (binary)
1 << 2 = 4 (decimal) = 0000100 (binary)
1 << 3 = 8 (decimal) = 0001000 (binary)

It shifts a specific pattern (the left operand) to the left, the 'length' of the shift is determined by the right operand. It works with other numbers than 1; 3 << 2 = 12 because 0000011 (binary) shifted two places is 0001100. Translated to normal mathematics, a << b = a * 2^b.

The specific use of this pattern is that it is very easy to check if a certain option is set. Suppose I want my application to send notifications with badges and alerts. I pass the value UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert to the API, which is

UIRemoteNotificationTypeBadge = 0000001
UIRemoteNotificationTypeAlert = 0000100
                        total = 0000101 |

(the | is the bitwise OR operator; for every bit, the result is 1 if one or both of the corresponding bit of the operands is 1). The API can then check if the badge property is present with the & operator:

                        total = 0000101
UIRemoteNotificationTypeBadge = 0000001
                       result = 0000001 &

(the & is the bitwise AND operator; for every bit, the result is 1 if both of the corresponding bit of the operands is 1). The result is non-zero, so the badge property is present. Let's do the same with the sound property:

                        total = 0000101
UIRemoteNotificationTypeSound = 0000010
                       result = 0000000 &

The result is zero, so the badge property is not present.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109