title: Multiple permission types (roles) stored in database as single decimal
body: <p>I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:</p>
  
  <p><a href="/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types">What is the best way to handle multiple permission types?</a></p>
  
  <p>It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer</p>
  
  <p>I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.</p>
  
  <p>Here is the original answer in the off chance the other question gets deleted:</p>
  
  <p>"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.</p>
  
  <pre><code>[Flags]
  public enum Permission
  {
      VIEWUSERS = 1, // 2^0 // 0000 0001
      EDITUSERS = 2, // 2^1 // 0000 0010
      VIEWPRODUCTS = 4, // 2^2 // 0000 0100
      EDITPRODUCTS = 8, // 2^3 // 0000 1000
      VIEWCLIENTS = 16, // 2^4 // 0001 0000
      EDITCLIENTS = 32, // 2^5 // 0010 0000
      DELETECLIENTS = 64, // 2^6 // 0100 0000
  }
  </code></pre>
  
  <p>Then, you can combine several permissions using the AND bitwise operator. </p>
  
  <p>For example, if a user can view &amp; edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. 
  You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).</p>
  
  <p>Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."</p>