开发者

How can I display the desired value in ASCII code inputted by me?

开发者 https://www.devze.com 2023-01-18 15:47 出处:网络
I need Java code. Please help me. Example: when I enter the number in ASCII 0 the output will be nul 1 for soh

I need Java code. Please help me. Example: when I enter the number in ASCII

0 the output will be nul
1 for soh
2 for stx until it reaches the max number of ASCII.

Consider this code. It outputs an ASCII number. How can I reverse it?

String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
    char c = test.charAt( i );
    int j = (int) c;
    System.out.println开发者_如何学Go(j);
}


import java.io.*;
import java.lang.*;
    public class CharToASCII{
        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;// your work is done here
            System.out.println("ASCII OF "+c +" = " + j + ".");
            }
        }
      }


Just cast an integer value to char.:

int value = (int) 'a';
System.out.println((char) value);  // prints a

If you need some literal output for ASCII values below '0', you'll need a mapping from the integer value (the ASCII number) to the literal, like this:

String[] literals0to32 = {"NUL", "SOH", "STX", /* to be continued */ };

private static String toLiteral(int value) {

   if (value < 0 || value > 255)
      throw new IKnowThatIHaveToValidateParametersException();

   if (value < 32) 
     return literals0To32[value];
   else
     return (char) value;
}


You can print the corresponding Unicode Control Pictures, e.g. \u2400 for ␀ (nul).


class prg1{
    public static void main(char a){
        int b=(int)a;
        System.out.println("ASCII value ="+b);
    }
}


Try this:

public static void main(String[] args) {
    String a = "a";
    char b = a.charAt(0);
    int c = b;
    System.out.println(c);
}
0

精彩评论

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

关注公众号