Android UTF8 Encode string2BytesUTF8(String str)

Here you can find the source of string2BytesUTF8(String str)

Description

string Bytes UTF

Declaration

public static byte[] string2BytesUTF8(String str) 

Method Source Code

//package com.java2s;

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

    public static byte[] string2BytesUTF8(String str) {
        byte[] bufByte = new byte[str.length() * 3];

        int byteLen = char2ByteUTF8(str, 0, str.length(), bufByte, 0,
                bufByte.length, false);//from   w  w  w  .j av  a2  s . c  o  m
        byte[] ret = new byte[byteLen];
        System.arraycopy(bufByte, 0, ret, 0, byteLen);
        return ret;
    }

    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;
            } 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. char2ByteUTF8(String input, int inOff, int inEnd, byte[] output, int outOff, int outEnd, boolean getLengthFlag)
  2. getStringInUtf8(final String str)
  3. stringToUtf8Bytes(String string)
  4. utf8encode(String str)
  5. isValidUTF8(byte[] input)
  6. toUtf8Bytes(String data)
  7. toUtf8String(byte[] data)
  8. stringFromUtf8ByteArray(byte[] data)