Let's say I have this:
char registered = '®';
or an umlaut
, or whatever unicode character. How could I get its code?
To insert a Unicode character, type the character code, press ALT, and then press X. For example, to type a dollar symbol ($), type 0024, press ALT, and then press X. For more Unicode character codes, see Unicode character code charts by script.
People wanting to use Unicode characters in an SMS text message sent from a mobile device should find the Unicode character set included in their devices´ settings (Menu > Messages > Settings > SMS > Sending Preferences > Alphabet).
Just convert it to int
:
char registered = '®'; int code = (int) registered;
In fact there's an implicit conversion from char
to int
so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.
This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char
values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt()
.
Once you've got the UTF-16 code unit or Unicode code points, both of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+
, e.g. "U+0020"
for space.) That's beyond the scope of this question though, as we don't know what the requirements are.
A more complete, albeit more verbose, way of doing this would be to use the Character.codePointAt method. This will handle 'high surrogate' characters, that cannot be represented by a single integer within the range that a char
can represent.
In the example you've given this is not strictly necessary - if the (Unicode) character can fit inside a single (Java) char
(such as the registered
local variable) then it must fall within the \u0000
to \uffff
range, and you won't need to worry about surrogate pairs. But if you're looking at potentially higher code points, from within a String/char array, then calling this method is wise in order to cover the edge cases.
For example, instead of
String input = ...; char fifthChar = input.charAt(4); int codePoint = (int)fifthChar;
use
String input = ...; int codePoint = Character.codePointAt(input, 4);
Not only is this slightly less code in this instance, but it will handle detection of surrogate pairs for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With