5

I was wondering how they did come up with the way of setting permissions using chmod by just using numbers. For example:

1 is for execute
2 is for write
4 is for read

Any sum of those give a unique permission:

2+4   = 6 lets you write and read.
1+4   = 5 lets you execute and read
1+2+4 = 7 lets you execute, read and write

Is there an algorithm to this? Say for example I have 10 items and I want to give to a person a number and by just that number the person can tell which items I have chosen.

Pithikos
  • 18,827
  • 15
  • 113
  • 136

1 Answers1

4

Binary system. I.e. you represent 1, 2, 4, 8, 16, and so on with a 0-or-1-digit each. The last digit stands for 2^0=1, the second-last digit stands for 2^1=2, the next digit for 2^2=4, the next for 2^3=8 and so on.

Now, you associate an action (read/ex/write) with each digit.

A (more or less) surprising fact is the following: If you don't have just two options (i.e. if you do not just have true or false), but if you have more, you can adapt this pattern to the ternary system. Moreover, you can adapt this pattern for any base. The human system works for base 10.

phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • You get my upvote, but you really ought to expand on this—e.g., show which bits are mapped to which permissions (for user, group, and other, and also for the set-id and sticky bits). – derobert Oct 05 '11 at 19:38
  • @derobert: The question wasn't really about Unix permissions; it was just inspired by it. The question is about the general idea about representing several boolean values as one integer. – Aasmund Eldhuset Oct 05 '11 at 19:39
  • @AasmundEldhuset: Fair enough, I read it as more the Unix question. I guess some editing may be in order. Also, you may want to mention this isn't unique to base-2, you can e.g., encode 10 items as the OP mentions in base-10 (which actually makes a good example, because everyone knows base-10)... (edit: looks like you did) – derobert Oct 05 '11 at 19:42
  • @Pithikos: They (probably) just thought: "Ok, lets take the last bit and let it represent some boolean variable; now we take the second-last bit and let it represent some other boolean variable; now, we take the next digit to represent some other other bool variable. Now, we pack all the digits into a base-2-number." – phimuemue Oct 05 '11 at 19:45
  • @phimuemue -- base-8 number: octal. – Pete Wilson Oct 05 '11 at 19:49
  • The thing noone explained me is that the reason this works is that the sum of digits before the Nth number will ALWAYS be smaller than the Nth number itself. So 1+2+4+8+16 < 32. In fact the sum is always Nth-1. – Pithikos Oct 21 '11 at 14:00