[java] Convert character to ASCII numeric value in java

I have String name = "admin";
then I do String charValue = name.substring(0,1); //charValue="a"

I want to convert the charValue to its ASCII value (97), how can I do this in java?

This question is related to java string ascii

The answer is


For this we could straight away use String classe's

    input.codePointAt(index);

I would like to give one more suggestion as to get whole of string converted to corresponding ascii codes, using java 8 for example, "abcde" to "979899100101".

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

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

just a different approach

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

bytes[0] will represent ascii of a.. and thus the other characters in the whole array.


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

Convert the char to int.

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

Also :

int ascii = name.charAt(0);

Or you can use Stream API for 1 character or a String starting in Java 1.8:

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

It's simple, get the character you want, and convert it to int.

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

I know this has already been answered in several forms but here is my bit of code with a look to go through all the characters.

Here is the code, started with the class

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

}


If you want the ASCII value of all the characters in a String. You can use this :

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

and if you want ASCII of a single character in a String you can go for :

(int)a.charAt(index);

I was trying the same thing, but best and easy solution would be to use charAt and to access the indexes we should create an integer array of [128] size.

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.

In case if you want to display ascii values of complete String, you need to do this.

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

Your output, in this case, will be: Ascii value of a is: 97 Ascii value of d is: 100 Ascii value of m is: 109 Ascii value of i is: 105 Ascii value of n is: 110


You can check the ASCIIĀ“s number with this code.

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

If I am wrong, apologies.


The easy way to do this is:

For whole String into 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 output is:

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


Here, abc.charAt(i) gives the single character of String array: When we assign each character to integer type then, the compiler do type conversion as,

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

But, for single character:

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


using Java 9 => String.chars()

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

output - [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]


Instead of this:

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

You should use the charAt() method.

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

The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.

But why do you want to do this anyway? What are you going to do with the value?

If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII.


An easy way for this is:

    int character = 'a';

If you print "character", you get 97.


One line solution without using extra int variable:

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

If you wanted to convert the entire string into concatenated ASCII values then you can use this -

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

wherein you will get 979899 as output.

Credit to this.

I just copied it here so that it would be convenient for others.


Just cast the char to an int.

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

The value of number will be 97.


As @Raedwald pointed out, Java's Unicode doesn't cater to all the characters to get ASCII value. The correct way (Java 1.7+) is as follows :

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

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
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to ascii

Detect whether a Python string is a number or a letter Is there any ASCII character for <br>? UnicodeEncodeError: 'ascii' codec can't encode character at special name Replace non-ASCII characters with a single space Convert ascii value to char What's the difference between ASCII and Unicode? Invisible characters - ASCII How To Convert A Number To an ASCII Character? Convert ascii char[] to hexadecimal char[] in C Convert character to ASCII numeric value in java