Posts

Showing posts from September, 2011

Using bitwise operation OR & AND on integer for validation

Today I'm going to revisit bitwise OR (|) and AND (&) operation on integer specifically for role based security checking scenario. Scenario : There are few reason why bitwise operation on integer is needed in an application, but more frequently seen to be use for validation for e.g. user's role validation. This is a very useful scenario, the application stores only one integer on the database to represent all the role that is assigned to that user. And on the application, user role is usually represented as Enum (Enum is a kind of integer). Lets get into some coding. Following is small C# program I wrote on LINQPad. void Main() { // PART (A) Define user role int Public = 1; int Sales = 2; int Marketing = 4; int Engineering = 8; // PART (B) Assign some role to user. Assigned role is stored as an integer in the db of the user table. int currentUser1 = Sales | Public; int currentUser2 = Marketing | Public; int currentUser3 = Sales | Marketing | Public; // D