Decodes a JTF16-encoded string - Java java.lang

Java examples for java.lang:String Unicode

Description

Decodes a JTF16-encoded string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] encoded = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(decodeJTF(encoded));
    }/*from   ww w  . j  a v  a2 s . co  m*/

    /**
     * Decodes a JTF16-encoded string
     * @author Killer99, Whired
     * @param encoded the encoded bytes
     * @return the decoded string
     */
    public static String decodeJTF(final byte[] encoded) {
        int offset = 0;
        int length = encoded.length;
        final char[] chars = new char[length];
        int count = 0;
        for (length += offset; offset != length; ++count) {
            final byte v1 = encoded[offset++];
            if (v1 >= 0) {
                chars[count] = (char) v1;
            } else if (offset != length) {
                final byte v2 = encoded[offset++];
                if (v2 >= 0) {
                    chars[count] = (char) (v1 & 0x7f | (v2 & 0x7f) << 7);
                } else if (offset != length) {
                    chars[count] = (char) (v1 & 0x7f | (v2 & 0x7f) << 7 | (encoded[offset++] & 0x3) << 14);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        return new String(chars, 0, count);
    }
}

Related Tutorials