0

Apologise for a vague title.

What is the best way to pass a finite number of properties(e.g. read, write, execute, ...). I think I could do this like these permissions - count the sum of some numbers assigned to properties - 1,2,4,8,16... Is it the best easy to do this and what algorithm should I use to get the summands - for example if I have 17 - how could I calculate that this is 16 and 1?

Thanks.

  • 1
    Sounds like a good case for bitmasking constants, like PHP's Error level setting - http://stackoverflow.com/questions/5319475/bitmask-in-php-for-settings/5320235#5320235 – Mark Baker Sep 11 '13 at 12:48

1 Answers1

1

You could use Bitwise Operators. This way you can compare the actual bits of an integer, Here's how it works:

Bit Pattern
8 4 2 1
1 0 0 0 = 8
0 1 1 1 = 7
0 1 1 0 = 6
0 1 0 1 = 5
0 1 0 0 = 4
0 0 1 1 = 3
0 0 1 0 = 2
0 0 0 1 = 1
0 0 0 0 = 0

So,

6 & 4 = 4

Means show me the bits that are present in both 6 and 4. Compare '0 1 1 0' and '0 1 0 0' and you will see that the second bit '4' is the only bit populated in both, so return 4.

Or

7 & 3 = 3

Means show me the bits that are present in both 7 and 3. Compare '0 1 1 1' and '0 0 1 1' and you will see that the third (2) and fourth (1) bits are populated in both, so return 3 (2 + 1).

Buchow_PHP
  • 410
  • 3
  • 10