Belgi
Belgi

Reputation: 15062

How to convert String (of length 1) to the associated int value of ASCII code (0-255)?

In my code I have A string with length 1, I want to convert it to the int associated with the character value of (extended) ASCII code (0-255).

For example:

"A"->65
"f"->102

Upvotes: 0

Views: 2375

Answers (2)

Mob
Mob

Reputation: 11096

You mean char? All you really need to do is cast the character to an int.

            String a = "A";
            int c = (int) a.charAt(0);
            System.out.println(c);

Outputs 65

Here's a more comprehensive code.

  import java.io.*;
    import java.lang.*;

      public class scrap{
      public static void main(String args[]) throws IOException{
      BufferedReader buff =
      new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter the char:");
      String str = buff.readLine();
      for ( int i = 0; i < str.length(); ++i ){
      char c = str.charAt(i);
      int j = (int) c;
      System.out.println("ASCII OF "+c +" = " + j + ".");
      }
      }

  }

Upvotes: 3

user684934
user684934

Reputation:

int asciiCode = (int)A.charAt(0);

Or, if you really need to get the ascii code for the string literal "A", instead of a string referenced by variable A:

int asciiCode = (int)"A".charAt(0);

Upvotes: 4

Related Questions