开发者

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 valu开发者_Python百科e of (extended) ASCII code (0-255).

For example:

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


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);


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 + ".");
      }
      }

  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜