Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert character to ASCII numeric value in java

Tags:

java

string

ascii

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?

like image 874
Celta Avatar asked Oct 15 '22 22:10

Celta


People also ask

What is ASCII value of A to Z in Java?

In Java, the char variable stores the ASCII value of a character (number between 0 and 127) rather than the character itself. The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from 65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122.

How do I encode a Java String as ASCII?

Convert String to ASCII 2.1 We can use String. getBytes(StandardCharsets. US_ASCII) to convert the string into a byte arrays byte[] , and upcast the byte to int to get the ASCII value. 2.2 Java 9, there is a new API String.


Video Answer


2 Answers

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.
like image 382
Rahul Avatar answered Oct 17 '22 10:10

Rahul


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.

like image 55
stinepike Avatar answered Oct 17 '22 10:10

stinepike