Ascii to number 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?

ASCII? Are you sure that’s what you want? Java uses the UTF-16 character encoding of the Unicode character set (just like JavaScript, .NET, VBA, VB4/5/6, NCHAR, NVARCHAR, NTFS, Windows API, …). The answers fall into several categories: answering about ASCII explicitly, answering about UTF-16 and answering about ASCII via several shortcutted leaps from UTF-16 (and also some are just plain wrong).

22 Answers 22

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. 

@VKSingla — Agreed its not required, but it improves readability and will help the OP in understanding.

Why create another char variable? Even if you want the cast why not to do this that way? int ascii = (int)name.charAt(0);

ASCII characters have 7-bit codes from 0 to 127. So no need to use int. byte can perfectly store any code.

I was looking to convert the int to char, the cast hint helped me to do it the other way around from the answer.

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.

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?

Читайте также:  Проверка глобальной переменной php

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 .

Perfect answer. Type casting is just a short-cut that’s not accurate. Glad your answer came at start so people don’t misunderstand concept.

The reason I have need to know the ASCII string is because I’ve got Unicode data coming into a backend process that needs to place pure ASCII somewhere else, and I need to when I’m getting non-Unicode. Usually when users are copy pasting from MS Word (e.g. curved double and single quotes, long dashes, etc.). To mention StandardCharsets.US_ASCII is the correct thing to do, but that doesn’t tell the original questioner how to use it.

Call the above with: String string = «This “is” strange»; System.out.println(«strings=» + string); System.out.println(displayAsciiCode(string, true)); System.out.println(displayAsciiCode(string, false)); The result is: strings=This “is” strange T=84 h=104 i=105 s=115 =32 “=63 i=105 s=115 ”=63 =32 s=115 t=116 r=114 a=97 n=110 g=103 e=101 T=84 h=104 i=105 s=115 =32 ¬=-30 タ=-128 ワ=-100 i=105 s=115 ¬=-30 タ=-128 ン=-99 =32 s=115 t=116 r=114 a=97 n=110 g=103 e=101

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.

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

Источник

How to convert ASCII code (0-255) to its corresponding character?

How can I convert, in Java, the ASCII code (which is an integer from [0, 255] range) to its corresponding ASCII character? For example:

this is not a duplicate as mentioned above. This is not conversion from integer but from char (ascii)

Not a duplicate of «How to convert from int to String?». anyway, FWIW, ASCII is only 7-bits with values [0, 127] 😉

@Belgi — you’ll need to explicitly state your encoding if you want to correctly transcode values 128-255. The term «extended ASCII» is not meaningful.

10 Answers 10

For MIDP 2 / CLDC 1.1 based platforms (which don’t have Character.toString(char) , stackoverflow.com/a/6210938/923560 provides additional solutions.

What is the reason for the (char) designation? In other words, why can’t I just put Character.toString(i); ? (Java noob)

Note that this will not work for the Integer type, you will get a «java.lang.Integer cannot be cast to java.lang.Character» error. Add a cast to int first, e.g.: Character.toString((char)(int)myInteger);

Читайте также:  Поиск утечки памяти java

The i values (0-255) would be from the ISO-8859-1 character set. (The question asker declined to identify which «extended ASCII» [vague term] was wanted, except by accepting this answer.)

System.out.println((char)65); would print «A»

REPL tip: If you happen to be using JShell (Java 9) you can omit the System.out. Just type (char) 65 to find out what character it is.

Assuming the integer is, as you say, between 0 and 255, you’ll get an array with a single character back from Character.toChars , which will become a single-character string when passed to String.valueOf .

Using Character.toChars is preferable to methods involving a cast from int to char (i.e. (char) i ) for a number of reasons, including that Character.toChars will throw an IllegalArgumentException if you fail to properly validate the integer while the cast will swallow the error (per the narrowing primitive conversions specification), potentially giving an output other than what you intended.

Assuming that the integer is in the range 0 to 255 (as you state that you do . and as the question specifies), it is unnecessary and suboptimal to use toChars .

You’re completely correct that something like Character.toString((char) i) is faster than String.valueOf(Character.toChars(i)) . Running a quick benchmark of converting 1,000,000 random integers in the given range (100 times, to be safe) on my machine gives an average time of 153.07 nanoseconds vs. 862.39 nanoseconds. However, in any interesting application, there will be far more important things to optimize. The added value of the safe, deterministic handling and ease of expanding outside the [0,255] range should it be required outweighs the minor performance hit.

Источник

Ascii to Integer

Could someone tell me why str.charAt(i) — ‘0’ is considered and what does it do? Also, why is the result multiplied by 10? Thanks!

2 Answers 2

By doing Str.CharAt(i) -‘0’ you just convert the caracter to the real number value provided that character is in 0 .. 9 range.

The result = result * 10 thing is to «shift» previous result to the left (decimal base), since a new digit has been detected (and added to the result)

This code is probably doing a string to integer conversion, also a bad one since it seems that 12AAA34 would be converted to 1234 since non-digit charts are just skipped. It would be better if parsing stopped as soon as a non-digit char was found, like C atoi does (still accepting/skipping spaces)

First of all this Str.CharAt(i) — ‘0’ is considered because both Str.CharAt(i) and ‘0’ returns Characters which have their ascii values to be integers.

Читайте также:  Событие onload

It means that taking the value of the String Str fetch the character at index number i of the String( Str ). For example consider this String Emil . Then «Emil».CharAt(0); will give me E . But E has an ascii value of 69 which is an integer. Also 0 has an ascii value of 48 . So «Emil».CharAt(0); — 0 is equivalent to 69 — 48 (thus the subtraction of two integer values) and returns and integer of 21 .

It( Str.CharAt(i) — 0 ) is added to the results of results * 10 because Str.CharAt(i) — 0 returns a Character which can also be recognise as an Integer(ascii) in java.

Take a look at this stackoverflow page which also have an ascii to character table to make you understand more.

Источник

Java — Convert a String of letters to an int of corresponding ascii?

I want to convert a String, lets say «abc» , to an int with the corresponding ascii: in this example, 979899 . I’ve run into two problems: 1) what I wrote only works for characters whose ascii is two characters long and 2) since these numbers get very big, I can’t use longs and I’m having trouble utilizing BigIntegers. This is what I have so far:

BigInteger mInt = BigInteger.valueOf(0L); for (int i = 0; i

Instead of valueOf(), just use Constructor, new BigInteger(String.valueOf(yourCode));docs.oracle.com/javase/1.5.0/docs/api/java/math/…

3 Answers 3

What’s wrong with doing all the concatenation first with a StringBuilder and then creating a BigInteger out of the result? This seems to be much simpler than what you’re currently doing.

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

you don’t have to play the number game. (pow 100 etc). just get the number string, and pass to constructor.

final String s = "abc"; String v = ""; final char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) < v += String.valueOf((int) chars[i]); >//v = "979899" now BigInteger bigInt = new BigInteger(v); //BigInteger BigDecimal bigDec = new BigDecimal(v); // or BigDecimal 

Assuming the string s is going to be long, it would probably be better to use a StringBuilder performance-wise. Repetitive string concatenations can be expensive.

To handle n-digit numbers, you will have to multiply by a different power of ten each time. You could do this with a loop:

BigInteger appendDigits(BigInteger total, int n) < for (int i = n; i >0; i /= 10) total = total.multiply(10); return total.plus(new BigInteger(n)); > 

However, this problem really seems to be about manipulating strings. What I would probably do is simply accumulate the digits int a string, and create a BI from the String at the end:

StringBuilder result = new StringBuilder(); for (char c : mString.getBytes()) result.append(String.valueOf(c)); return new BigInteger(result.toString()); 

Источник

Оцените статью