简体   繁体   中英

Char to int and back again

I want to find an integer representation of a character, then later on find a character representation of an int.

My current solution is this, but it doesn't work:

String s = "A"
Integer b = Character.getNumericValue(s.toCharArray()[0]);    // 10
char c = Character.toChars(b)[0];                             // (blank)

How should i do this?

int b = s.charAt(0); // 65
char c = (char) b  // 'A'

There's a misunderstanding in how Character.getNumericValue(char) works.

Returns the int value that the specified Unicode character represents. For example, the character '\Ⅼ' (the roman numeral fifty) will return an int with a value of 50.

The letters AZ in their uppercase ('\A' through '\Z'), lowercase ('\a' through '\z'), and full width variant ('\A' through '\Z' and '\a' through '\z') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

from the java docs .

In other words:
The method getNumericValue does not produce the UTF-16 value of the specified character, but attempts to produce a numeric value - in the sense that '0' will produce 0 - from the given value. And 'A' corresponds to 10 in hex.

But 10 is not the UTF16 value corresponding to 'A'.

A correct way of converting a char to it's corresponding UTF16-value would be to use one of the codepoint-methods from Character . Or if you're absolutely positive, all values will be of the BMP, you can use

char c = 'A';
int i = (int) c;

In this case Character.toChars(int) will also work.

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