Printf with "% d" numbers starting at 0 (ex "0102"), giving an unexpected response (eg "66")
This is because when the first digit of a number (an integer constant) is 0
(and the second must not be x
or x
), the compiler interprets it as an octal number. Printing it with %d
will give you the decimal value.
To print an octal value you must use %o
specifier
printf("%o", n);
6.4.4.1 Integer constants:
An integer constant starts with a digit but has no period or exponent. It can have a prefix that indicates its base and a suffix that indicates its type.
A decimal constant starts with a nonzero digit and consists of a sequence of decimal digits. An octal constant is prefixed with 0, optionally followed by a sequence of digits from 0 to 7 . A hexadecimal constant is prefixed with 0x or 0X in decimal digits and the letters a (or A) through f (or F) with values ββ10-15, respectively.
Integer constants:
1. Decimal constants : must not start with 0
.
12 125 3546
2. Octal constants : must start with 0
.
012 0125 03546
3. Hexadecimal constants : always starts with 0x
or 0x
.
0xf 0xff 0X5fff
source to share