There is a major gotcha associated with getting an ASCII code of a char
value.
In the proper sense, it can't be done.
It's because char
has a range of 65535
whereas ASCII is restricted to 128
. There is a huge amount of characters that have no ASCII representation at all.
The proper way would be to use a Unicode code point which is the standard numerical equivalent of a character in the Java universe.
Thankfully, Unicode is a complete superset of ASCII. That means Unicode numbers for Latin characters are equal to their ASCII counterparts. For example, A
in Unicode is U+0041
or 65
in decimal. In contrast, ASCII has no mapping for 99% of char-s. Long story short:
char ch = 'A';
int cp = String.valueOf(ch).codePointAt(0);
Furthermore, a 16-bit primitive char
actually represents a code unit, not a character and is thus restricted to Basic Multilingual Plane, for historical reasons. Entities beyond it require Character objects which deal away with the fixed bit-length limitation.