Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Subtract '0' from char to get an int... why does this work?

Tags:

java

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?

like image 482
ledneb Avatar asked Nov 30 '10 20:11

ledneb


People also ask

Why you can subtract 0 from a character and have it convert to the numerical value?

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.

What happens when you subtract a char from a char?

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.

What does minus 0 Do Java?

charAt(x) returns a char: int foo = bar. charAt(1); It seems that subtracting '0' from the char is casting it to an integer.


2 Answers

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

like image 178
Lukas Eder Avatar answered Nov 02 '22 02:11

Lukas Eder


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.

like image 44
DwB Avatar answered Nov 02 '22 01:11

DwB