Java UTF Convert utfToString(byte[] src, int srcIndex, int len)

Here you can find the source of utfToString(byte[] src, int srcIndex, int len)

Description

Return bytes in Utf8 representation as a string.

License

Apache License

Parameter

Parameter Description
src The array holding the bytes.
srcIndex The start index from which bytes are converted.
len The maximum number of bytes to convert.

Return

String representation.

Declaration

public static String utfToString(byte[] src, int srcIndex, int len) 

Method Source Code

//package com.java2s;
/*/*from ww w. j a  va 2s .c  o  m*/
 * Copyright 2013 Alexander Shabanov - http://alexshabanov.com.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Return bytes in Utf8 representation as a string.
     * @param src       The array holding the bytes.
     * @param srcIndex  The start index from which bytes are converted.
     * @param len       The maximum number of bytes to convert.
     * @return String representation.
     */
    public static String utfToString(byte[] src, int srcIndex, int len) {
        char dst[] = new char[len];
        int len1 = utfToChars(src, srcIndex, dst, 0, len);
        return new String(dst, 0, len1);
    }

    /**
     * Convert `len' bytes from utf8 to characters.
     * Parameters are as in {@see System#arraycopy}
     * @param src       The array holding the bytes to convert.
     * @param srcIndex  The start index from which bytes are converted.
     * @param dst       The array holding the converted characters.
     * @param dstIndex  The start index from which converted characters are written.
     * @param len       The maximum number of bytes to convert.
     * @return First index in `dst' past the last copied char.
     */
    public static int utfToChars(byte[] src, int srcIndex, char[] dst, int dstIndex, int len) {
        int i = srcIndex;
        int j = dstIndex;
        int limit = srcIndex + len;
        while (i < limit) {
            int b = src[i++] & 0xFF;
            if (b >= 0xE0) {
                b = (b & 0x0F) << 12;
                b = b | (src[i++] & 0x3F) << 6;
                b = b | (src[i++] & 0x3F);
            } else if (b >= 0xC0) {
                b = (b & 0x1F) << 6;
                b = b | (src[i++] & 0x3F);
            }
            dst[j++] = (char) b;
        }
        return j;
    }
}

Related

  1. UTFToGB(String ostr)
  2. utfToGBK(byte[] srcByte)