简体   繁体   中英

Convert character to ASCII numeric value in java

I have String name = "admin";
then I do String charValue = name.substring(0,1); //charValue="a" 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?

Very simple. Just cast your char as an int .

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

In your case, you need to get the specific Character from the String first and then cast it.

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

Though cast is not required explicitly, but its improves readability.

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

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.

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 .

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.

Convert the char to int.

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

Also :

int ascii = name.charAt(0);

Just cast the char to an int.

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

The value of number will be 97.

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

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

}

An easy way for this is:

    int character = 'a';

If you print "character", you get 97.

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

String name = "admin";
int ascii = name.charAt(0);
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);
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
}

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)

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

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]

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.

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

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

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()));
char c = 'a';
byte b = (byte) (c & 0x7F);

One line solution without using extra int variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM