Reputation: 57
I'm unsure of how to set my if statements using bitwise operators, I got it to work using conditonal operators and summing up the enum however I want to know how I should be able to do it with & or |.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
typedef enum eUser_Permissions
{
VIEW =1,
ADD=2,
EDIT=4,
DELETE=8
} User_Permissions;
void print_permissions(char* username, int permissions);
int main(void){
int x = VIEW;
int j = VIEW | ADD | EDIT;
int s = VIEW | ADD | EDIT | DELETE;
print_permissions("S", s);
print_permissions("X", x);
print_permissions("J", j);
return 0;
}
void print_permissions(char* username, int permissions)
{
if (permissions ==15)
{
printf("%s's permissions (%d): VIEW ADD EDIT DELETE", username, permissions);
printf("\n");
}
if (permissions ==1)
{
printf("%s's permissions (%d): VIEW", username, permissions);
printf("\n");
}
if (permissions == 7)
{
printf("%s's permissions (%d): VIEW ADD EDIT", username, permissions);
printf("\n");
}
Upvotes: 1
Views: 87
Reputation: 223689
You initially set the permissions using the bitwise OR operator, so just do the same when checking:
if (permissions == (VIEW | ADD | EDIT | DELETE))
If you want to check each condition individually, use a bitwise AND between the passed in value and the permission in question:
printf("%s's permissions (%d):", username, permissions);
if (permissions & VIEW) {
printf(" VIEW");
}
if (permissions & ADD ) {
printf(" ADD");
}
if (permissions & EDIT ) {
printf(" EDIT");
}
if (permissions & DELETE) {
printf(" DELETE");
}
printf("\n");
Upvotes: 1