[英]How to convert Special Character 'β' to its unicode
我想使用代码将'β'转换为它的 uni-code 'U+03B2' 。 但是当我尝试转换它时,我得到了'63'作为它的整数值,它是'?'的值。 特点。 它没有转换为正确的值。 有什么方法可以获得'β'的正确值,即十进制'946' ,十六进制'03B2' 。
我试过了:
int code = 'β';
byte[] b = { (byte)code };
String s = new String(b, "UTF-8");
以下是各种形式的值:
int code = 'β';
System.out.println(code); // 946 as an int
System.out.println(Integer.toString(code)); // 946 as a String
System.out.println(Integer.toHexString(code)); // 3b2
System.out.println(String.format("%04x", code)); // 03b2
System.out.println(String.format("%04x", code).toUpperCase()); // 03B2
(编辑:看过其他答案后,我现在知道您可以使用格式字符串"%04X"
直接以大写形式获取答案。)
如果 UTF-8 不是您的平台默认字符编码,您需要确保源文件以 UTF-8 编码保存,然后在编译时指定 -encoding -encoding UTF-8
选项(或其他支持的字符编码) β
)。
您的代码是错误的,因为您正在使用一个 16 位的char
并将其切成两半,只保留低 8 位。 缩小强制转换可能会破坏数据; 他们必须明确地写出来,让你思考你在做什么。
你的代码是这样的:
int code = 0x000003B2;
byte[] b = { 0xB2 };
字节序列 0xB2 不是有效的 UTF-8,因此使用字符串s
的替换字符
(U+FFFD) 对其进行解码。 如果您的输出设备未配置为显示该字符,它将在输出时与不同的替换字符交换, ?
.
如果您在编辑器和编译器中得到正确的编码,这应该可以工作:
int code = 'β';
System.out.printf("U+%04X%n", code);
String s = "β";
int i = s.codePointAt(0);
System.out.printf("U+%04X", i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.