Encodes a string in JTF16 - Java java.lang

Java examples for java.lang:String Unicode

Description

Encodes a string in JTF16

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String string = "java2s.com";
        System.out.println(java.util.Arrays.toString(encodeJTF(string)));
    }//  w w w .j ava  2 s .  com

    /**
     * Encodes a string in JTF16
     * @author Killer99, Whired
     * @param string the string to encode
     * @return the encoded bytes
     */
    public static byte[] encodeJTF(final String string) {

        // Skip the linear-time counting iteration
        //int len = 0;
        // Skip this linear iteration
        final char[] chrArr = string.toCharArray();
        //      for (final char c : chrArr) {
        //         if (c < 0x80) {
        //            len++;
        //         }
        //         else if (c < 0x3fff) {
        //            len += 2;
        //         }
        //         else {
        //            len += 3;
        //         }
        //      }
        final byte[] encoded = new byte[string.length() * 3];//len];
        int idx = 0;
        for (final int chr : chrArr) {
            if (chr < 0x80) {
                encoded[idx++] = (byte) chr;
            } else if (chr < 0x3fff) {
                encoded[idx++] = (byte) (chr | 0x80);
                encoded[idx++] = (byte) (chr >>> 7);
            } else {
                encoded[idx++] = (byte) (chr | 0x80);
                encoded[idx++] = (byte) (chr >>> 7 | 0x80);
                encoded[idx++] = (byte) (chr >>> 14);
            }
        }

        // Should be faster
        final byte[] sizedEncoded = new byte[idx];
        System.arraycopy(encoded, 0, sizedEncoded, 0, idx);
        return sizedEncoded;
    }
}

Related Tutorials