Dear community,
int number = atoi("0123");
In this piece of code number will be 123 and not 0123. Why is that?
Thank you in advanced.
Niek
Dear community,
int number = atoi("0123");
In this piece of code number will be 123 and not 0123. Why is that?
Thank you in advanced.
Niek
It's not. 0123 and 123 are exactly the same numbers.
You don't show the rest of your code so I have to assume that you're using serial.print in which case you need to remember that serial.print does not print leading zeroes.
You can read up on sprintf() if you want to see leading zeroes.
sterretje:
It's not. 0123 and 123 are exactly the same numbers.
Not in a C program they're not! ![]()
TheMemberFormerlyKnownAsAWOL:
Not in a C program they're not!
As human readable text, they are ![]()
atoi() always parses using base 10.
If you want to parse octal numbers (or any other base), use strtol().
If the leading zero is important, like it is a phone number or a room number in a building with "floor zero" then it is a mistake to store it in an integer. Keep it as a string.
And yes, in C code,
int number = 0123;
the compiler will take that as an Octal number and give you a result that is really unexpected.
TheMemberFormerlyKnownAsAWOL:
Not in a C program they're not!
Serial.begin(9600);
int x = 0123;
Serial.println(x, DEC); //shows: 83 decimal
int y = 123;
Serial.println(y, DEC); //shows: 123 decimal