• Post Reply Bookmark Topic Watch Topic
  • New Topic

Convert more than one character at a time to ASCII value  RSS feed

 
Gozie Morah
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have String that is equal to "ABCDEF". I want to make it where I get the ASCII value of CD which is supposed to be 6768, but no matter what I do all I get is 135 and I'm only able to convert one character at a time. Is there another way I can find the ASCII value of a slice?
 
Stephan van Hulst
Saloon Keeper
Posts: 7976
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

Show us the code you're using to convert, and make sure to use code tags around it, like [code]this[/code].
 
Gozie Morah
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

String alpha= "ABCDEF"
int slice1 = alpha.charAt(2);
int slice2 = alpha.charAt(3);
int slicecom= slice1 + slice2;
System.out.println(+slicecom);
 
Carey Brown
Saloon Keeper
Posts: 3315
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

ASCII is one character per byte (aka 8-bits). This will only work if the characters in question are strictly ASCII.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Being a numbers guy, I noticed that 135 is 67 + 68.

So I suspected that you were using the + operator in the expectation that it would concatenate two String, but actually adding two numbers. And when I looked at your code, that is just what you did.

What you need to do, then, is to convert your so-called "ASCII" value to a String before applying the + operator.

(I said "so-called" because the number you get when you convert a Java character to an integer value is the Unicode code point which corresponds to that character. ASCII happens to represent the first 128 code points of the much larger Unicode domain, so calling them "ASCII" is like drawing a black and white picture of a rainbow.)
 
Stephan van Hulst
Saloon Keeper
Posts: 7976
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To get a "slice", use the substring() method on your String.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!