Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert array of strings to a single integer

I am trying to create a "permissions" system where I can store all the permissions a user has. Currently, all the permissions of a user are stored as an array inside the database:

[
    'role.users.view',
    'role.users.manage',
    'role.users.delete'
    ...
]

However, the more permissions I create, the bigger the size of the database becomes. As a result, I would like to be able to store all this array as an unique string/integer/identifier which allows me to efficiently transform the array above into a single integer – let’s say the array of strings above becomes the number 1290481294. My initial thought would have been to construct an integer based on whether the permission is on/off – resulting in an integer like 10101010101 – but this number would also become ridiculously long; so I’m trying to find a more efficient approach to this.

I am completely sure there is already an existing technique for this, but I don’t really know how it is called or where I can document myself upon the subject.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tl;dr: I am trying to convert the array of strings above into a single, as-short-as-possible integer.

>Solution :

If you’re working with Python you could use this.

all_permissions = [ # List of all permissions (prefarably unique)
    'role.users.view',
    'role.users.manage',
    'role.users.delete'
]

permission_flag = 1
permission_flags = {}
for permission in all_permissions: # Initiate flags
    permission_flags[permission] = permission_flag
    permission_flag *= 2

all_permissions = [] # Clear all_permissions, we don't need it anymore
permissions = [ # Old user permissions
    'role.users.view',
    'role.users.delete',
    'role.users.delete'
]

permission_identifier = 0
for permission in permissions:
    permission_identifier |= permission_flags[permission] # Bitwise or

print(permission_identifier)

Ouput:

5

This is correct, because: 2^0 + 2^2 = 1 + 4 = 5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading