Hi I've got this code for converting String to int manually.
int num = 0;
for(int i = 0; i < length(number); i++) {
num *= 10;
num += number.charAt(i) - '0';
println("i :" + num);
}
Why do we subtract '0' at the end?
The method .charAt(int position) returns a single character from your number string. Since your string contains a number you will receive a character which contains a digit (0 - 9). The next step would be to convert this character to an int.
a naive solution would be:
char digit = number.charAt(i);
if (digit == '0') {
num += 0;
} else if (digit == '1') {
num += 1;
}
But we can use the ASCII values of our characters to simplify this. Take a look at this ASCII table (only the columns 'Dec' and 'Chr'). You will see that the character 0 has in fact a value of 48. So if we substract 48 from our character we retrieve the correct value:
int num = digit - 48;
This can even be more simplified by directly placing the character which will be replaced by the compiler:
int num = digit - '0';
example:
character '4' has an ASCII value of 52. If we substract 48 we get 4 which is the wanted result.
If number is String interpreted as number, the number.charAt(i) is a character from '0' —— '9', if you represent the chars as numbers, it would be 0 —— 9, moved to the code of '0' (something like '0' —— '0' + 9), so for getting the exact digit (as int: number), you should subtract the code of '0' from the char.
ASCII value of '0' is 48, '1' is 49 and so on. Example: If a charactor variable "ch" is containing '5' now ASCII value of '5' is 53. If we want to perform mathematical operation '5' we have to convert it into int so we have to get it's integer value so we use ch-'0' (that means '5'-'0' that means 53-48 that is 5) by doing this we get integer value of '5'. Now we can perform mathematical operation on that. If you perform mathematical operation on '5', compiler will treat it as 53.
charis really ashortinterpreted in a different way. So in a way, you're calculating "distance from'0'"int i = 'F' - 'A';What is the value ofFandA? What is the value of for example'3'? (hint: it's not 3)