Java 如何以我输入的 ASCII 码显示所需的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3863815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:00:03  来源:igfitidea点击:

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

javaascii

提问by jhoanne

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

我需要Java代码。请帮我。示例:当我以 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?

考虑这个代码。它输出一个 ASCII 数字。我怎样才能扭转它?

String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
    char c = test.charAt( i );
    int j = (int) c;
    System.out.println(j);
}

采纳答案by Jigar Joshi

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

回答by Andreas Dolk

Just cast an integer value to char.:

只需将整数值转换为 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:

如果您需要一些文字输出低于 '0' 的 ASCII 值,您将需要从整数值(ASCII 数字)到文字的映射,如下所示:

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

回答by trashgod

You can print the corresponding Unicode Control Pictures, e.g. \u2400for ? (nul).

您可以打印相应的Unicode 控制图片,例如\u2400用于 ? ( nul).

回答by pracheth

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

回答by Akhil Ajay

Try this:

尝试这个:

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