I'm trying to let my tool/script determine if a logged in user has the correct permission to use the tool. however Discord is responding with a permission int.
It seems that I have to check permission using a bitwise operator, But from everything that i've googled or searched almost everything I find seems completely irrelevant.
Is there a tool or a sample script that I can study, to determine how this calculation is made?
Thank you in advance!
Imagine that you have
4 different actions you want to allow or disallow for each user:
Let's create a 4-characters string of
0. The first character in the string represents the user's possibility to
create post action. The second character –
update post, third –
read post and the fourth –
delete post. For example, if a user has permissions
1001 then he can create posts and delete posts, but can't update and read.
What is the most efficient way to store these permissions? We have only
1 in every position of our string, so we can store this data not inside the string but inside the binary representation of the number. So, the user's permission will be some decimal number, and every bit of this number will represent permission for a specific action.
For example, our permission string
1001 will be just decimal number
= 1*2^0 + 0*2^1 + 0*2^2 + 1*2^3).
We can represent every permission as binary:
But how can we check that user has specific permission or has a group of permissions? It's easy, let's use bitwise operator
If user permission equals
1001 & 1000 = 1000,
1000 > 0– user can create posts
1001 & 0100 = 0000,
0000 == 0– user can't update posts
1001 & 0010 = 0000,
0000 == 0– user can't read posts
1001 & 0001 = 0001,
0001 > 0– user can delete posts
User contributions licensed under CC BY-SA 3.0