Convertir un caractère en valeur numérique ASCII en java

j'ai String name = "admin";

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

je veux convertir le char en sa valeur ASCII (97), Comment puis-je faire cela en java?

120
demandé sur EJoshuaS 2013-05-09 13:30:22

19 réponses

très simple. Il suffit de lancer votre char comme un int .

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

dans votre cas, vous avez besoin d'obtenir le caractère spécifique de la chaîne d'abord et ensuite le lancer.

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

bien que cast ne soit pas explicitement requis, mais il améliore la lisibilité.

int ascii = character; // Even this will do the trick.
201
répondu SudoRahul 2013-05-09 09:44:17

une approche différente

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

bytes[0] représentera ascii d'un.. et donc les autres personnages de l'ensemble du tableau.

42
répondu stinepike 2013-05-09 09:37:37

au lieu de ceci:

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

vous devez utiliser la méthode charAt() .

char c = name.charAt(0); // c='a'
int ascii = (int)c;
18
répondu christopher 2013-05-09 09:32:13

si vous voulez convertir la chaîne entière en valeurs ASCII concaténées, alors vous pouvez utiliser ce -

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

où vous obtiendrez 979899 en sortie.

crédit à ce .

Je l'ai juste copié ici pour qu'il soit pratique pour les autres.

9
répondu user1721904 2017-05-23 12:18:22

les nombreuses réponses qui prétendent montrer comment faire tout cela sont fausses parce que les caractères Java ne sont pas des caractères ASCII. Java utilise un encodage multibyte de caractères Unicode. Le jeu de caractères Unicode est un super jeu D'ASCII. Il peut donc y avoir des caractères dans une chaîne Java qui n'appartiennent pas à ASCII. Comme ces caractères N'ont pas de valeur numérique ASCII, il est impossible de savoir comment obtenir la valeur numérique ASCII d'un caractère Java.

mais pourquoi tu veux faire ça quand même? Qu'allez-vous faire avec la valeur?

si vous voulez la valeur numérique pour pouvoir convertir la chaîne Java en chaîne ASCII, la question est" Comment dois-je encoder une chaîne Java en ASCII". Pour cela, utilisez l'objet StandardCharsets.US_ASCII.

8
répondu Raedwald 2016-03-23 10:22:39

Convertir le char en int.

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

aussi:

int ascii = name.charAt(0);
4
répondu Vineet Singla 2013-05-09 09:33:25

vient de lancer le char à un int.

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

la valeur de number sera 97.

1
répondu Daniel Lerps 2013-05-09 09:31:52

c'est simple, obtenir le personnage que vous voulez, et le convertir en int.

String name = "admin";
int ascii = name.charAt(0);
1
répondu Ricardo Cacheira 2013-05-09 09:42:49

je sais que cela a déjà été répondu sous plusieurs formes, mais voici mon morceau de code avec un regard pour passer en revue tous les caractères.

voici le code, commencé par la classe

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

}

1
répondu gcclinux 2016-01-07 15:43:59
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);
1
répondu Sandeepp Sah 2016-03-22 14:03:15
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
}
1
répondu iAsghar Hussain 2017-01-07 06:38:17
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]);
        }
    }
}
1
répondu yeswanth g 2017-03-09 15:23:10

comme @Raedwald l'a souligné, L'Unicode Java ne répond pas à tous les caractères pour obtenir une valeur ASCII. La manière correcte (Java 1.7+) est la suivante:

byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)
1
répondu Karthik R 2017-04-19 11:12:26

un moyen facile pour cela est:

    int character = 'a';

si vous imprimez "caractère", vous obtenez 97.

1
répondu ktlawal 2018-02-22 03:58:14

ou vous pouvez utiliser L'API Stream pour 1 caractère ou une chaîne commençant en Java 1.8:

public class ASCIIConversion {
    public static void main(String[] args) {
        String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
        text.chars()
                .forEach(System.out::println);
    }
}
1
répondu matua 2018-08-12 07:47:45

vous pouvez vérifier le numéro ASCIIs avec ce code.

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

si je me trompe, toutes mes excuses.

0
répondu Sin Nombre 2016-03-23 10:18:48

si vous voulez la valeur ASCII de tous les caractères d'une chaîne. Vous pouvez utiliser ceci:

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

et si vous voulez ASCII d'un seul caractère dans une chaîne de caractères, vous pouvez choisir:

(int)a.charAt(index);
0
répondu Vikram Singh 2017-02-11 18:54:04

j'essayais la même chose, mais la meilleure solution serait d'utiliser charAt et pour accéder aux Index nous devrions créer un tableau entier de taille [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.

dans le cas où vous voulez afficher des valeurs ascii de chaîne complète, vous devez le faire.

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

Votre sortie, dans ce cas, sera: Valeur Ascii d'Un is: 97 Valeur Ascii de D est: 100 Valeur Ascii de m est: 109 La valeur Ascii de i est de: 105 Valeur Ascii de n est: 110

0
répondu Siddhartha Thota 2017-12-30 20:44:26

Le moyen facile de le faire est:

pour chaîne entière en 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]);
      }
    }
}


la sortie est:

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


Ici, abc.charAt(i) donne le caractère unique du tableau de cordes: Lorsque nous assignons chaque caractère au type entier puis, la conversion de type do du compilateur comme,

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

mais, pour un seul caractère:

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

0
répondu Sushant 2017-12-31 15:38:24