• Post Reply Bookmark Topic Watch Topic
  • New Topic

charAt for string off by 48?  RSS feed

 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was recently using charAt() in a program in order to separate a string of numbers into its component numbers. However, I noticed that they were all off by 48, so I made a test program to confirm this. Here is the program:

The output of the program is as follows:

test = abc123
firstChar = a
secondChar = b
thirdChar = c
firstInt = 49
secondInt = 50
thirdInt = 51

Why are the integers all off by 48? Is there any way to solve this other than just subtracting 48? It just seems weird to me that they would be off like this.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you really think that the character code for '1' is the value 1?

I introduce you to the great ASCII chart:



Infer what you will from it.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. Yeah, Java uses UTF-8, but the first 128 characters are based on ASCII.

(And please UseCodeTags; I added them for you this time.)
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also a character and an int are printed in different ways.

$ java m
0
48
0


 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault wrote:P.S. Yeah, Java uses UTF-8, but the first 128 characters are based on ASCII.

Really? I thought it used UTF-16; or has that changed recently?

@Louis: For your purposes it doesn't really matter, because what Bear said still applies.

Winston
 
Vijay Kalkundri
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Based on the output that is desired , i thought this solves the issue ...





- Vijay K
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!