【问题标题】:Convert character to ASCII numeric value in java在java中将字符转换为ASCII数值
【发布时间】:2013-05-03 17:44:44
【问题描述】:

我有String name = "admin";
然后我做String charValue = name.substring(0,1); //charValue="a"

我想将charValue 转换为其 ASCII 值 (97),如何在 java 中执行此操作?

【问题讨论】:

  • JW 将 String char 编译。可能您想将变量重命名为String ch
  • ASCII?你确定那是你想要的吗? Java 使用 Unicode 字符集的 UTF-16 字符编码(就像 JavaScript、.NET、VBA、VB4/5/6、NCHAR、NVARCHAR、NTFS、Windows API 等)。答案分为几类:明确回答有关 ASCII 的问题,回答有关 UTF-16 的问题,以及通过从 UTF-16 的几个捷径飞跃回答有关 ASCII 的问题(还有一些是完全错误的)。

标签: java string ascii


【解决方案1】:

非常简单。只需将您的 char 转换为 int

char character = 'a';    
int ascii = (int) character;

在您的情况下,您需要先从字符串中获取特定的字符,然后再进行转换。

char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.

虽然没有明确要求强制转换,但它提高了可读性。

int ascii = character; // Even this will do the trick.

【讨论】:

  • @VKSingla - 同意它不是必需的,但它提高了可读性并有助于 OP 理解。
  • 为什么要创建另一个 char 变量?即使您想要演员阵容,为什么不这样做呢? int ascii = (int)name.charAt(0);
  • @R.J - 好吧,我没想到
  • ASCII 字符有 0 到 127 的 7 位代码。所以不需要使用 int。 byte 可以完美存储任何代码。
  • 我正在寻找将 int 转换为 char,转换提示帮助我从答案中反过来做。
【解决方案2】:

只需将 char 转换为 int。

char character = 'a';
int number = (int) character;

number 的值将是 97。

【讨论】:

    【解决方案3】:

    而不是这个:

    String char = name.substring(0,1); //char="a"
    

    您应该使用charAt() 方法。

    char c = name.charAt(0); // c='a'
    int ascii = (int)c;
    

    【讨论】:

    • 请记住“char”是 Java 中的保留字。
    【解决方案4】:

    将 char 转换为 int。

        String name = "admin";
        int ascii = name.toCharArray()[0];
    

    还有:

    int ascii = name.charAt(0);
    

    【讨论】:

      【解决方案5】:

      很简单,得到你想要的字符,然后转成int。

      String name = "admin";
      int ascii = name.charAt(0);
      

      【讨论】:

        【解决方案6】:

        如果您想将整个字符串转换为连接的 ASCII 值,那么您可以使用它 -

            String str = "abc";  // or anything else
        
            StringBuilder sb = new StringBuilder();
            for (char c : str.toCharArray())
            sb.append((int)c);
        
            BigInteger mInt = new BigInteger(sb.toString());
            System.out.println(mInt);
        

        您将在其中得到 979899 作为输出。

        归功于this

        我只是复制到这里,方便其他人使用。

        【讨论】:

          【解决方案7】:

          只是一种不同的方法

              String s = "admin";
              byte[] bytes = s.getBytes("US-ASCII");
          

          bytes[0] 将代表 a.. 的 ascii 以及整个数组中的其他字符。

          【讨论】:

            【解决方案8】:
            String str = "abc";  // or anything else
            
            // Stores strings of integer representations in sequence
            StringBuilder sb = new StringBuilder();
            for (char c : str.toCharArray())
                sb.append((int)c);
            
             // store ascii integer string array in large integer
            BigInteger mInt = new BigInteger(sb.toString());
            System.out.println(mInt);
            

            【讨论】:

            • 虽然这段代码可以回答这个问题,但最好解释一下它的作用并添加一些参考。
            【解决方案9】:

            我知道这已经以多种形式得到了回答,但这是我的一些代码,可以查看所有字符。

            这是代码,从类开始

            public class CheckChValue {  // Class name
            public static void main(String[] args) { // class main
            
                String name = "admin"; // String to check it's value
                int nameLenght = name.length(); // length of the string used for the loop
            
                for(int i = 0; i < nameLenght ; i++){   // while counting characters if less than the length add one        
                    char character = name.charAt(i); // start on the first character
                    int ascii = (int) character; //convert the first character
                    System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
                }
            }
            

            }

            【讨论】:

            • Java 对stringchar 使用Unicode。 Unicode 中的文本单元是字素,它是一个基本代码点,后跟零个或多个组合代码点。 Java 中的代码点以 UTF-16 编码,这可能需要一个或两个 16 位代码单元 (char) 作为代码点。要迭代代码点,请参阅answer。例如,代码应该已经准备好迎接即将到来的 U+1F91E HAND WITH INDEX AND MIDDLE FINGERS CROSSED 代码点。
            【解决方案10】:

            您可以使用此代码检查 ASCII 码。

            String name = "admin";
            char a1 = a.charAt(0);
            int a2 = a1;
            System.out.println("The number is : "+a2); // the value is 97
            

            如果我错了,请道歉。

            【讨论】:

              【解决方案11】:

              声称如何做到这一点的几个答案都是错误的,因为 Java 字符不是 ASCII 字符。 Java 使用 Unicode 字符的多字节编码。 Unicode 字符集是 ASCII 的超集。因此,Java 字符串中可能存在不属于 ASCII 的字符。这样的字符没有ASCII数值,所以问如何获取Java字符的ASCII数值是无解的。

              但是为什么你还是要这样做?你打算怎么处理这个值?

              如果您需要数值以便将 Java 字符串转换为 ASCII 字符串,真正的问题是“如何将 Java 字符串编码为 ASCII”。为此,请使用对象StandardCharsets.US_ASCII

              【讨论】:

              • 完美答案。类型转换只是一个不准确的捷径。很高兴您一开始就给出了答案,这样人们就不会误解概念。
              • 我需要知道 ASCII 字符串的原因是因为我有 Unicode 数据进入后端进程,需要将纯 ASCII 放在其他地方,当我得到非-Unicode。通常当用户从 MS Word 复制粘贴时(例如弯曲的双引号和单引号、长破折号等)。提到 StandardCharsets.US_ASCII 是正确的做法,但这并没有告诉原始提问者如何使用它。
              • public static String displayAsciiCode(String s, boolean useStandard) { String r = "";字节[] ascii = null; if (useStandard) { ascii = s.getBytes(StandardCharsets.US_ASCII); for (int i=0; i
              • 调用上面的代码: String string = "This "is"奇怪"; System.out.println("strings=" + string); System.out.println(displayAsciiCode(string, true)); System.out.println(displayAsciiCode(string, false));结果是: strings=这个“很”奇怪 T=84 h=104 i=105 s=115 =32 “=63 i=105 s=115 ”=63 =32 s=115 t=116 r=114 a= 97 n=110 g=103 e=101 T=84 h=104 i=105 s=115 =32 ¬=-30 タ=-128 ワ=-100 i=105 s=115 ¬=-30 タ=-128ン=-99 =32 s=115 t=116 r=114 a=97 n=110 g=103 e=101
              【解决方案12】:
              String name = "admin";
              char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
              
              for(int i=0; i<ch.length; i++)
              {
                  System.out.println(ch[i]+
                                     "-->"+
                                     (int)ch[i]); //this will print both character and its value
              }
              

              【讨论】:

                【解决方案13】:

                如果你想要一个字符串中所有字符的 ASCII 值。你可以用这个:

                String a ="asdasd";
                int count =0;
                for(int i : a.toCharArray())
                    count+=i;
                

                如果你想要字符串中单个字符的 ASCII,你可以选择:

                (int)a.charAt(index);
                

                【讨论】:

                  【解决方案14】:
                  public class Ascii {
                      public static void main(String [] args){
                          String a=args[0];
                          char [] z=a.toCharArray();
                          for(int i=0;i<z.length;i++){ 
                              System.out.println((int)z[i]);
                          }
                      }
                  }
                  

                  【讨论】:

                  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
                  【解决方案15】:

                  正如@Raedwald 所指出的,Java 的 Unicode 并不能满足所有字符来获取 ASCII 值。正确的方式(Java 1.7+)如下:

                  byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
                  String asciiString = new String(asciiBytes);
                  //asciiString = Arrays.toString(asciiBytes)
                  

                  【讨论】:

                  • new String(byte[]) 使用了另一种字符编码——所谓的系统默认值,它会随着时间、机器和用户而变化;几乎从来没有用过。你所说的asciiString 仍然是 UTF-16,因为这就是 Java 的全部。
                  • @TomBlodget,我同意。但我认为 OP 想知道如何获取给定字符的 ASCII 表示。这只是一种编码,因为 java 不能做原始 ASCII
                  【解决方案16】:

                  我也在尝试同样的事情,但最好和简单的解决方案是使用 charAt 并访问我们应该创建一个 [128] 大小的整数数组的索引。

                  String name = "admin"; 
                  int ascii = name.charAt(0); 
                  int[] letters = new int[128]; //this will allocate space with 128byte size.
                  letters[ascii]++; //increments the value of 97 to 1;
                  System.out.println("Output:" + ascii); //Outputs 97
                  System.out.println("Output:" +  letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.
                  

                  如果你想显示完整字符串的 ascii 值,你需要这样做。

                  String name = "admin";
                  char[] val = name.toCharArray();
                  for(char b: val) {
                   int c = b;
                   System.out.println("Ascii value of " + b + " is: " + c);
                  }
                  

                  在这种情况下,您的输出将是: a的Ascii值为:97 d 的 Ascii 值为:100 m的Ascii值为:109 i 的 Ascii 值为:105 n的ascii值为:110

                  【讨论】:

                    【解决方案17】:

                    简单的方法是:

                    将整个字符串转换成ASCII:


                    public class ConvertToAscii{
                        public static void main(String args[]){
                          String abc = "admin";
                          int []arr = new int[abc.length()];
                          System.out.println("THe asscii value of each character is: ");
                          for(int i=0;i<arr.length;i++){
                              arr[i] = abc.charAt(i); // assign the integer value of character i.e ascii
                              System.out.print(" "+arr[i]);
                          }
                        }
                    }
                    


                    输出为:

                    THe asscii value of each character is: 97 100 109 105 110


                    这里,abc.charAt(i) 给出了 String 数组的单个字符: 当我们将每个字符分配给整数类型时,编译器会进行类型转换,

                    arr[i] = (int) character // Here, every individual character is coverted in ascii value

                    但是,对于单个字符:

                    String name = admin; asciiValue = (int) name.charAt(0);// for character 'a' System.out.println(asciiValue);

                    【讨论】:

                      【解决方案18】:

                      一个简单的方法是:

                          int character = 'a';
                      

                      如果你打印“字符”,你会得到 97。

                      【讨论】:

                        【解决方案19】:

                        或者您可以使用 Stream API 处理 1 个字符或从 Java 1.8 开始的字符串:

                        public class ASCIIConversion {
                            public static void main(String[] args) {
                                String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
                                text.chars()
                                        .forEach(System.out::println);
                            }
                        }
                        

                        【讨论】:

                          【解决方案20】:

                          使用 Java 9 => String.chars()

                          String input = "stackoverflow";
                          System.out.println(input.chars().boxed().collect(Collectors.toList()));
                          

                          输出 - [115、116、97、99、107、111、118、101、114、102、108、111、119]

                          【讨论】:

                            【解决方案21】:

                            为此,我们可以直接使用 String 类的

                                input.codePointAt(index);
                            

                            我想再提出一个建议,使用 java 8 将整个字符串转换为相应的 ascii 代码 例如,“abcde”到“979899100101”。

                                String input = "abcde";
                                System.out.println(
                                        input.codePoints()
                                                .mapToObj((t) -> "" + t)
                                                .collect(joining()));
                            

                            【讨论】:

                              【解决方案22】:

                              不使用额外 int 变量的单行解决方案:

                              String name = "admin";
                              System.out.println((int)name.charAt(0));
                              

                              【讨论】:

                                猜你喜欢
                                • 2021-06-16
                                • 2011-10-03
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多