简体   繁体   中英

Converting UTF-16BE to UTF-8 in Java ME

I am writing an app in Java ME for old Symbian devices (and not only them). I have a problem. I am trying to draw emojis using png images. They are stored on some server in 2 folders. The first folder does not contain new emojis after year 2017 and I have to change my code. Old code to guess the filename:

Integer.toHexString((int) text.toCharArray()[ii-1]).toUpperCase()+Integer.toHexString((int) text.toCharArray()[ii]).toUpperCase()+".png"

This helps me to convert emoji with integer codes of 2 symbols 55356 57147 to D83CDF3B.png Now I need to get f09f8cbb.png from the same emoji. The website https://unicode-table.com/en/1F33B/ says that UTF-8 F0 9F 8C BB and UTF-16BE D8 3C DF 3B is the same. How can I convert from UTF16BE to UTF-8? All the code I had found on the.net is in C or Javascript and does not suite to me. On StackOverflow, I also found this code

try {
    // Convert from Unicode to UTF-8
    String string = "\u003c";
    byte[] utf8 = string.getBytes("UTF-8");

    // Convert from UTF-8 to Unicode
    string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}

But it returns the same String as I give to it.

This helped me in Java ME, in compliance to Java 1.3.

static String bytesToHex(byte[] bytes) {
        final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
    

String HexOfString(String str) {
   byte[] utfString = str.getBytes("UTF-8");
   return bytesToHex(utfString);
}

From emoji I got "F09F8CBB"

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