Java UTF8 Encode utf8Encode(String s)

Here you can find the source of utf8Encode(String s)

Description

This method is required to work around a stupid bug in Sun's JDK String.getBytes("UTF-8") (bug #4628881).

License

Open Source License

Declaration

public static byte[] utf8Encode(String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from   w ww.j a v  a 2  s. c o m*/
     * This method is required to work around a stupid bug
     * in Sun's JDK String.getBytes("UTF-8") (bug #4628881).
     */
    public static byte[] utf8Encode(String s) {
        final char[] chars = s.toCharArray();
        int elen;

        // Compute encoded length
        elen = 0;
        for (int i = 0; i < s.length(); i++) {
            int ch = chars[i];
            if (ch >= 0x0001 && ch <= 0x007f)
                elen++;
            else if (ch == 0x0000 || (ch >= 0x0080 && ch <= 0x07ff))
                elen += 2;
            else
                elen += 3;
        }

        // Do the actual encoding
        byte[] data = new byte[elen];
        elen = 0;
        for (int i = 0; i < s.length(); i++) {
            int ch = chars[i];
            if (ch >= 0x0001 && ch <= 0x007f)
                data[elen++] = (byte) ch;
            else if (ch == 0x0000 || (ch >= 0x0080 && ch <= 0x07ff)) {
                data[elen++] = (byte) (0xc0 | ((ch >> 6) & 0x1f));
                data[elen++] = (byte) (0x80 | (ch & 0x3f));
            } else {
                data[elen++] = (byte) (0xe0 | ((ch >> 12) & 0x0f));
                data[elen++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
                data[elen++] = (byte) (0x80 | (ch & 0x3f));
            }
        }
        return data;
    }
}

Related

  1. utf8Code(String str)
  2. Utf8codeCheck(String text)
  3. utf8Encode(final Collection col)
  4. utf8Encode(final String s)
  5. utf8Encode(final String value)
  6. utf8Encode(String str)
  7. utf8Encode(String str)
  8. Utf8Encode(String string)
  9. utf8Encode(String url)