简体   繁体   中英

How to convert Special Character 'β' to its unicode

I want to convert 'β' to its uni-code 'U+03B2' using code. But when i tried to convert it, I am getting '63' as its integer value which is the value of '?' character. It is not converting to its correct value. Is there any way to get the correct value of 'β' ie decimal '946' , hex '03B2' .

I have tried:

   int code = 'β';
   byte[] b = { (byte)code };
   String s = new String(b, "UTF-8");

Here is the value in various forms:

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

(Edit: Having seen the other answers I now know that you can use the format string "%04X" to get the answer in upper case form directly.)

If UTF-8 is not your platform default character encoding, you'll need to make sure that the source file is saved in UTF-8 encoding, and then specify the -encoding UTF-8 option when compiling (or another character encoding that supports β ).

Your code is wrong because you are taking a char , which is 16 bits, and chopping it in half, keeping only the lower 8 bits. Narrowing casts can destroy data; they are required to be written explicitly to make you think about what you are doing.

Your code is like this:

int code = 0x000003B2;
byte[] b = { 0xB2 };

The byte sequence 0xB2 isn't valid UTF-8, so it's decoded with the replacement character, (U+FFFD) in the string s . If your output device isn't configured to display that character, it will be swapped with a different replacement character on output, ? .

If you get the encoding correct in your editor and compiler, this should work:

int code = 'β';
System.out.printf("U+%04X%n", code);
String s = "β";
int i = s.codePointAt(0);
System.out.printf("U+%04X", i);

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