Java UTF from ToUTF(String s)

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

Description

Converts String to UTF-8 String.

License

Open Source License

Parameter

Parameter Description
s String to convert

Return

converted String

Declaration

public static String ToUTF(String s) 

Method Source Code

//package com.java2s;
//License from project: MIT License 

public class Main {
    /**/*ww w. j a v a2 s.com*/
     * Converts String to UTF-8 String. Code from Colibry IM messenger used
     * 
     * @param s
     *            String to convert
     * @return converted String
     */
    public static String ToUTF(String s) {
        int i = 0;
        StringBuffer stringbuffer = new StringBuffer();

        for (int j = s.length(); i < j; i++) {
            int c = (int) s.charAt(i);
            if ((c >= 1) && (c <= 0x7f)) {
                stringbuffer.append((char) c);
            }
            if (((c >= 0x80) && (c <= 0x7ff)) || (c == 0)) {
                stringbuffer.append((char) (0xc0 | (0x1f & (c >> 6))));
                stringbuffer.append((char) (0x80 | (0x3f & c)));
            }
            if ((c >= 0x800) && (c <= 0xffff)) {
                stringbuffer.append(((char) (0xe0 | (0x0f & (c >> 12)))));
                stringbuffer.append((char) (0x80 | (0x3f & (c >> 6))));
                stringbuffer.append(((char) (0x80 | (0x3f & c))));
            }
        }

        return stringbuffer.toString();
    }
}

Related

  1. toUTF(String inpara)
  2. toUTF(String str)
  3. toUTF(String... str)
  4. toUTF8(byte[] outputBuffer, String string, char[] workingBuffer)
  5. toUtf8(final String string)