Android UTF8 Encode char2ByteUTF8(String input, int inOff, int inEnd, byte[] output, int outOff, int outEnd, boolean getLengthFlag)

Here you can find the source of char2ByteUTF8(String input, int inOff, int inEnd, byte[] output, int outOff, int outEnd, boolean getLengthFlag)

Description

char Byte UTF

Declaration

public static int char2ByteUTF8(String input, int inOff, int inEnd,
            byte[] output, int outOff, int outEnd, boolean getLengthFlag) 

Method Source Code

//package com.java2s;

public class Main {
    private static byte[] outputByte = new byte[3];

    public static int char2ByteUTF8(String input, int inOff, int inEnd,
            byte[] output, int outOff, int outEnd, boolean getLengthFlag) {
        char inputChar;
        int outputSize;

        int charOff = inOff;
        int byteOff = outOff;

        while (charOff < inEnd) {
            inputChar = input.charAt(charOff);
            if (inputChar < 0x80) {
                outputByte[0] = (byte) inputChar;
                outputSize = 1;/*from ww  w.j  a  v  a  2  s.c om*/
            } else if (inputChar < 0x800) {
                outputByte[0] = (byte) (0xc0 | ((inputChar >> 6) & 0x1f));
                outputByte[1] = (byte) (0x80 | (inputChar & 0x3f));
                outputSize = 2;
            } else {
                outputByte[0] = (byte) (0xe0 | ((inputChar >> 12)) & 0x0f);
                outputByte[1] = (byte) (0x80 | ((inputChar >> 6) & 0x3f));
                outputByte[2] = (byte) (0x80 | (inputChar & 0x3f));
                outputSize = 3;
            }
            if (getLengthFlag) {
                byteOff += outputSize;
            } else {
                if ((byteOff + outputSize) > outEnd) {
                    return -1;
                }
                for (int i = 0; i < outputSize; i++) {
                    output[byteOff++] = outputByte[i];
                }
            }
            charOff++;
        }
        return byteOff - outOff;
    }
}

Related

  1. bytesUtf8(int c)
  2. bytes2StringUTF8(byte[] buf)
  3. bytes2StringUTF8(byte[] buf, int bufOffset, int bufLength, boolean bigEndian)
  4. bytes2charsUTF8(byte[] buf, int bufOffset, int bufLength, char[] cbuf, boolean bigEndian)
  5. bytesUTF8len(byte[] buf, int bufOffset, int bufLength)
  6. getStringInUtf8(final String str)
  7. stringToUtf8Bytes(String string)
  8. utf8encode(String str)
  9. isValidUTF8(byte[] input)