Here you can find the source of UTF16toUTF8(CharSequence s, int offset, int len, byte[] result, int resultOffset)
public static int UTF16toUTF8(CharSequence s, int offset, int len, byte[] result, int resultOffset)
//package com.java2s; /*/*from w w w . j ava2 s . c o m*/ * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.0 * * 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 { /** Writes UTF8 into the byte array, starting at offset. The caller should ensure that * there is enough space for the worst-case scenario. * @return the number of bytes written */ public static int UTF16toUTF8(CharSequence s, int offset, int len, byte[] result, int resultOffset) { final int end = offset + len; int upto = resultOffset; for (int i = offset; i < end; i++) { final int code = (int) s.charAt(i); if (code < 0x80) result[upto++] = (byte) code; else if (code < 0x800) { result[upto++] = (byte) (0xC0 | (code >> 6)); result[upto++] = (byte) (0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { result[upto++] = (byte) (0xE0 | (code >> 12)); result[upto++] = (byte) (0x80 | ((code >> 6) & 0x3F)); result[upto++] = (byte) (0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end - 1)) { int utf32 = (int) s.charAt(i + 1); // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); i++; result[upto++] = (byte) (0xF0 | (utf32 >> 18)); result[upto++] = (byte) (0x80 | ((utf32 >> 12) & 0x3F)); result[upto++] = (byte) (0x80 | ((utf32 >> 6) & 0x3F)); result[upto++] = (byte) (0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character result[upto++] = (byte) 0xEF; result[upto++] = (byte) 0xBF; result[upto++] = (byte) 0xBD; } } return upto - resultOffset; } }