Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can someone explain this ???

 
Rob Hopping
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've set convertionValue equal to (binaryString.charAt(0)) but when I print them out I get two different answers.

The following produces:

13
3
51

Why is it addind 48 to convertionValue?


// main line of program
public static void main (String[] args) {

String binaryString = ("3677895775421");
int convertionValue;

convertionValue = (binaryString.charAt(0));

System.out.println(binaryString.length());
System.out.println(binaryString.charAt(0));
System.out.println(convertionValue);
}
}
 
Dun Dagda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because charAt will return the ASCII code of the character at that position in the String. The ASCII code of the character 0 (zero) is 48, character 1 is ASCII 49, etc.
So to convert the character code for the character "1" to its numerical equivalent, you need to subtract 48 from the character code.

DD
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See http://www.asciitable.com/
 
Dun Dagda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's something that might help you out.


Try pasting this into a .java file and compiling and running it yourself.

DD
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic