获取一个字符的Unicode值

有什么办法在Java中,以便我可以得到任何字符的Unicode等价物? 例如

假设一个方法getUnicode(char c) 。 调用getUnicode('÷')应返回\u00f7

你可以在这里使用一行代码来完成任何Java char:

 System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) ); 

但是,它只能用于Unicode 3.0以上的Unicode字符,这就是为什么我精简了你可以做任何Java字符。

因为Java是在Unicode 3.1出现之前devise的,所以Java的char原语不足以表示Unicode 3.1和以上:没有一个“一个Unicode字符到一个Java字符”映射了(而不是一个怪异的黑客使用)。

所以你真的要在这里检查你的需求:你需要支持Java字符或任何可能的Unicode字符?

如果你有Java 5,使用char c = ...; String s = String.format ("\\u%04x", (int)c); char c = ...; String s = String.format ("\\u%04x", (int)c);

如果您的源不是Unicode字符( char )而是string,则必须使用charAt(index)来获取位置index处的Unicode字符。

不要使用codePointAt(index)因为它将返回24位值(完整的Unicode),它不能用4个hex数字表示(它需要6个)。 请参阅文档以获取解释 。

[编辑]说清楚:这个答案不使用Unicode,而是Java用来表示Unicode字符(即代理对)的方法,因为char是16位,Unicode是24位。 问题应该是:“如何将char转换为4位hex数字”,因为它不是Unicode(真的)。

 private static String toUnicode(char ch) { return String.format("\\u%04x", (int) ch); } 
 char c = 'a'; String a = Integer.toHexString(c); // gives you---> a = "61" 

我在网上find了这个漂亮的代码。

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Unicode { public static void main(String[] args) { System.out.println("Use CTRL+C to quite to program."); // Create the reader for reading in the text typed in the console. InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { String line = null; while ((line = bufferedReader.readLine()).length() > 0) { for (int index = 0; index < line.length(); index++) { // Convert the integer to a hexadecimal code. String hexCode = Integer.toHexString(line.codePointAt(index)).toUpperCase(); // but the it must be a four number value. String hexCodeWithAllLeadingZeros = "0000" + hexCode; String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros.substring(hexCodeWithAllLeadingZeros.length()-4); System.out.println("\\u" + hexCodeWithLeadingZeros); } } } catch (IOException ioException) { ioException.printStackTrace(); } } } 

来源文章

你使用Unicode的挑剔,因为与Java更简单,如果你写你的程序使用“dec”值或(HTML代码),那么你可以简单地转换数据types之间的字符和int

 char a = 98; char b = 'b'; char c = (char) (b+0002); System.out.println(a); System.out.println((int)b); System.out.println((int)c); System.out.println(c); 

给出这个输出

 b 98 100 d 

首先,我得到了字符的高端。 之后,得到低端。 在HexString中转换所有的东西,并把前缀。

 int hs = (int) c >> 8; int ls = hs & 0x000F; String highSide = Integer.toHexString(hs); String lowSide = Integer.toHexString(ls); lowSide = Integer.toHexString(hs & 0x00F0); String hexa = Integer.toHexString( (int) c ); System.out.println(c+" = "+"\\u"+highSide+lowSide+hexa);