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 {
      if (code < 0xDC00 && (i < end - 1)) {
        int utf32=(int)s.charAt(i + 1);
        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;
        }
      }
      result[upto++]=(byte)0xEF;
      result[upto++]=(byte)0xBF;
      result[upto++]=(byte)0xBD;
    }
  }
  return upto - resultOffset;
}

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 { if ( code < 0xDC00 && ( i < end - 1 ) ) { int utf32 = ( int ) s . charAt ( i + 1 ) ; 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 ; } } result [ upto ++ ] = ( byte ) 0xEF ; result [ upto ++ ] = ( byte ) 0xBF ; result [ upto ++ ] = ( byte ) 0xBD ; } } return upto - resultOffset ; }
writes utf8 into the byte array , starting at offset . the caller should ensure that there is enough space for the worst - case scenario .
