This works fine:
int foo = bar.charAt(1) - '0';
Yet this doesn't - because bar.charAt(x) returns a char:
int foo = bar.charAt(1);
It seems that subtracting '0' from the char is casting it to an integer.
Why, or how, does subtracting the string '0' (or is it a char?) convert another char in to an integer?
All of the digit characters have values offset from the value of '0' . That means, if you have a character, let's say '9' and subtract '0' from it, you get the "distance" between the value of '9' and the value of '0' in the execution character set.
And as it turns out, when you do "character math", subtracting any alphabetical character from any other alphabetical character (of the same case) results in bits being flipped in such a way that, if you were to interpret them as an int , would represent the distance between these characters.
charAt(x) returns a char: int foo = bar. charAt(1); It seems that subtracting '0' from the char is casting it to an integer.
That's a clever trick. char's are actually of the same type / length as shorts. Now when you have a char that represents a ASCII/unicode digit (like '1'), and you subtract the smallest possible ASCII/unicode digit from it (e.g. '0'), then you'll be left with the digit's corresponding value (hence, 1)
Because char is the same as short (although, an unsigned short), you can safely cast it to an int. And the casting is always done automatically if arithmetics are involved
This is an old ASCII trick which will work for any encoding that lines the digits '0' through '9' sequentially starting at '0'. In Ascii, '0' is a character with value 0x30 and '9' is 0x39. Basically, if you have a character that is a digit, subtracting '0' "converts" it to it's digit value.
I have to disagree with @Lukas Eder and suggest that it is a terrible trick; because the intent of this action aproaches 0% obvious from code. If you are using Java and have a String
that contains digits and you want to convert said String
to an int
I suggest that you use Integer.parseInt(yourString);
.
This technique has the benifit of being obvious to the future maintenance programmer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With