What are octal literals?

Many languages ​​(starting at least until C. I am not familiar with the older ones) seem to have an agreement that integer literals can be written on the basis of 3 bases with the following notation:

  • 0xor 0xbase-16 number prefix (hex)
  • 0 base number prefix 8 (octal)
  • No prefix means base-10 (decimal) number

I understand the use of hexadecimal and decimal places. They are used universally, have various use cases where they make the code more readable (bitwise andwith 0x20000much clearer than with 131072), and it should not be confused (a number with the symbol 'x' or 'X' init does not make sense as a decimal number).

However, octal literals seem like a mistake to me. First of all, I have never seen them used, and it seems that I can’t imagine one use case where it will make the code more readable in order to use it in hex or decimal format. In addition, they can be confused with decimal numbers ( 010- this is a great decimal number without limiting the programming language).

So, do you use octal literals, are they some form of historical residual baggage from some time when they were useful, or is it just a mistake?

+4
source share
2 answers

A use case that comes to mind is file permissions, for example:

int retval = mkdir("/tmp/example", 0755);

. http://linux.die.net/man/2/mkdir

Unix :

  • : , ,
  • : , ,
  • other: , ,

755 : , , ; : , ; : , .

, Base 8 :

0 --> 000
1 --> 001
2 --> 010
3 --> 011
4 --> 100
5 --> 101
6 --> 110
7 --> 111

, - .

10, 0755 493, , 0x1ED.

8 .

+3

- UNIX- .

, , , .

:

-rw-------  1 dbush      dbush      14982 Dec  2 14:23 test.txt

, "" .

open, :

int fd = open("test.txt", O_WRONLY | O_CREAT, 0600);

:

0400 : read for owner
0200 : write for owner
0100 : execute for owner
0040 : read for group
0020 : write for group
0010 : execute for group
0004 : read for other
0002 : write for other
0001 : execute for other

3, , .

+2

Source: https://habr.com/ru/post/1618435/


All Articles