Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do those bitmasks actually work?

For example, this method from NSCalendar takes a bitmask:

- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts 

So options can be like:

NSUInteger options = kCFCalendarUnitYear; 

or like:

NSUInteger options = kCFCalendarUnitYear | kCFCalendarUnitMonth | kCFCalendarUnitDay; 

What I don't get is, how is this actually done? I mean: How can they pull out those values which are merged into options? If I wanted to program something like this, that can take a bitmask, how would that look?

like image 429
dontWatchMyProfile Avatar asked Mar 31 '10 17:03

dontWatchMyProfile


People also ask

How do Bitmasks work?

In Bitmasking, the idea is to visualize a number in the form of its binary representation. Some bits are “set” and some are “unset” , “set” means its value is 1 and “unset” means its value is 0. A “Bitmask” is simply a binary number that represents something.

What is the purpose of a bitmask?

Bitmasks. In binary operations, a bitmask can filter bit values using logical operations. For instance, a bitmask of 00001111 one operand of the boolean AND operation, it converts the first four bits of the other operand to 0. The final four bits will be unchanged.

What does a Bitwise and do?

Remarks. The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


1 Answers

Bitmasks are pretty basic really. You can think of it like this (C# until somebody can convert):

public enum CalendarUnits {     kCFCalendarUnitDay = 1, // 001 in binary     kCFCalendarUnitMonth = 2, // 010 in binary     kCFCalendarUnitYear = 4, // 100 in binary } 

You can then use the bitwise operators to combine the values:

// The following code will do the following // 001 or 100 = 101 // So the value of options should be 5 NSUInteger options = kCFCalendarUnitDay | kCFCalendarUnitYear; 

This technique is also often used in security routines:

public enum Priveledges {     User = 1,     SuperUser = 2,     Admin = 4 }  // SuperUsers and Admins can Modify // So this is set to 6 (110 binary) public int modifySecurityLevel = SuperUser | Admin; 

Then to check the security level, you can use the bitwise and to see if you have sufficient permission:

public int userLevel = 1; public int adminLevel = 4;  // 001 and 110 = 000 so this user doesn't have security if(modifySecurityLevel & userLevel == userLevel)  // but 100 and 110 = 100 so this user does if(modifySecurityLevel & adminLevel == adminLevel)     // Allow the action 
like image 164
Justin Niessner Avatar answered Sep 30 '22 03:09

Justin Niessner