Convert character to ASCII numeric value in java

JavaStringAscii

Java Problem Overview


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?

Java Solutions


Solution 1 - 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.

Solution 2 - Java

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.

Solution 3 - Java

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;

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

Convert the char to int.

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

Also :

int ascii = name.charAt(0);

Solution 7 - Java

Just cast the char to an int.

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

The value of number will be 97.

Solution 8 - Java

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

}

Solution 9 - Java

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

Solution 10 - Java

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

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

Solution 11 - Java

An easy way for this is:

    int character = 'a';

If you print "character", you get 97.

Solution 12 - Java

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

Solution 13 - Java

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
}

Solution 14 - Java

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)

Solution 15 - Java

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

Solution 16 - Java

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]

Solution 17 - Java

One line solution without using extra int variable:

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

Solution 18 - Java

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.

Solution 19 - Java

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

Solution 20 - Java

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

Solution 21 - Java

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:

97 100 109 105 110```
<hr>
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);
`

Solution 22 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCeltaView Question on Stackoverflow
Solution 1 - JavaRahulView Answer on Stackoverflow
Solution 2 - JavastinepikeView Answer on Stackoverflow
Solution 3 - JavachristopherView Answer on Stackoverflow
Solution 4 - JavaRaedwaldView Answer on Stackoverflow
Solution 5 - Javauser1721904View Answer on Stackoverflow
Solution 6 - JavaVineet SinglaView Answer on Stackoverflow
Solution 7 - JavaDaniel LerpsView Answer on Stackoverflow
Solution 8 - Javauser3025039View Answer on Stackoverflow
Solution 9 - Javayeswanth gView Answer on Stackoverflow
Solution 10 - JavaRicardo CacheiraView Answer on Stackoverflow
Solution 11 - JavaktlawalView Answer on Stackoverflow
Solution 12 - JavaSandeepp SahView Answer on Stackoverflow
Solution 13 - JavaiAsghar HussainView Answer on Stackoverflow
Solution 14 - JavaKarthik RView Answer on Stackoverflow
Solution 15 - JavamatuaView Answer on Stackoverflow
Solution 16 - JavaAnurag_BEHSView Answer on Stackoverflow
Solution 17 - JavaSatish HawalppagolView Answer on Stackoverflow
Solution 18 - JavaRaúl VelaView Answer on Stackoverflow
Solution 19 - JavaVikram SinghView Answer on Stackoverflow
Solution 20 - JavaSidd ThotaView Answer on Stackoverflow
Solution 21 - Javasusan097View Answer on Stackoverflow
Solution 22 - Javapiyush tyagiView Answer on Stackoverflow