Java UTF Convert utfToGBK(byte[] srcByte)

Here you can find the source of utfToGBK(byte[] srcByte)

Description

utf To GBK

License

Open Source License

Declaration

public static String utfToGBK(byte[] srcByte) throws Exception 

Method Source Code

//package com.java2s;

public class Main {

    public static String utfToGBK(byte[] srcByte) throws Exception {
        StringBuffer str = new StringBuffer();
        int len = srcByte.length;
        int char1, char2, char3;
        int count = 0;
        while (count < len) {
            char1 = srcByte[count] & 0xff;
            switch (char1 >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                count++;//from  w w  w  .  ja va2  s  .  co  m
                str.append((char) char1);
                break;
            case 12:
            case 13:
                count += 2;
                if (count > len) {
                    throw new Exception();
                }
                char2 = srcByte[count - 1];
                if ((char2 & 0xC0) != 0x80) {
                    throw new Exception();
                }
                str.append((char) (((char1 & 0x1F) << 6) | (char2 & 0x3F)));
                break;
            case 14:

                /* 1110 xxxx 10xx xxxx 10xx xxxx */
                count += 3;
                if (count > len) {
                    throw new Exception();
                }
                char2 = srcByte[count - 2];
                char3 = srcByte[count - 1];
                if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
                    throw new Exception();
                }
                str.append((char) (((char1 & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)));
                break;
            default:
                throw new Exception();
            }
        }
        return str.toString();
    }
}

Related

  1. UTFToGB(String ostr)
  2. utfToString(byte[] src, int srcIndex, int len)