Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Octal literals in C
In C, we can use octal literals by typing a zero before the actual number. For example, if an octal number is 25, then we have to write 025. Octal literals use base-8 numbering system and contain only digits 0-7.
Syntax
0octal_digits
Where octal_digits are valid octal digits (0-7).
Example
The following example demonstrates how to use octal literals in C −
#include <stdio.h>
int main() {
int a = 025; /* Octal 25 = Decimal 21 */
int b = 063; /* Octal 63 = Decimal 51 */
int c = 0777; /* Octal 777 = Decimal 511 */
printf("Decimal of 25(Octal) is %d<br>", a);
printf("Decimal of 63(Octal) is %d<br>", b);
printf("Decimal of 777(Octal) is %d<br>", c);
return 0;
}
Decimal of 25(Octal) is 21 Decimal of 63(Octal) is 51 Decimal of 777(Octal) is 511
How It Works
Octal literals are converted to decimal using base-8 system:
- 025 = 2×8¹ + 5×8? = 16 + 5 = 21
- 063 = 6×8¹ + 3×8? = 48 + 3 = 51
- 0777 = 7×8² + 7×8¹ + 7×8? = 448 + 56 + 7 = 511
Key Points
- Octal literals must start with
0(zero). - Only digits 0-7 are valid in octal literals.
- Using digits 8 or 9 will cause a compilation error.
- Octal literals are commonly used for file permissions in Unix systems.
Conclusion
Octal literals in C provide a convenient way to represent base-8 numbers by prefixing with zero. They are automatically converted to decimal values during compilation and are particularly useful in system programming.
Advertisements
