111 111 111

octal 777
decimal 511
binary 111 111 111
perm rwx rwx rwx
4 = r
2 = w
1 = x

rwx = 4+2+1 = 7
rw  = 4+2+0 = 6
r   = 4+0+0 = 4
r x = 4+0+1 = 5

7 = binary 111 = rwx
6 = binary 110 = rw-
5 = binary 101 = r-x
4 = binary 100 = r--
3 = binary 011 = -wx
2 = binary 010 = -w-
1 = binary 001 = --x
0 = binary 000 = ---

The full set of nine permission characters can then be grouped and summarized as three octal digits:

rwxr-x-wx  is  rwx|r-x|-wx  is 111|101|011 ==> the three digits 753
---r----x  is  ---|r--|--x  is 000|100|001 ==> the three digits 041
---------  is  ---|---|---  is 000|000|000 ==> the three digits 000
rwxrwxrwx  is  rwx|rwx|rwx  is 111|111|111 ==> the three digits 777

Convert octal to decimal using python:

>>> int('777', 8)

Decimal to binary:

>>> "{0:b}".format(511)
'111111111'

Bitwise AND with 07777 gives the last twelve bits of a number’s binary representation. With a Unix mode, this operation gives the permission or mode bits and discards any type information.

$ perl -e 'printf "%d\n", (stat "foo")[2] & 07777'  # decimal, not useful
420
$ perl -e 'printf "%o\n", (stat "foo")[2] & 07777'  # octal
644