Encode Chinese in GBK - Android Internationalization

Android examples for Internationalization:Chinese

Description

Encode Chinese in GBK

Demo Code

/**//w  w  w .java2s.  c o m
 * Project Name:JZGPingGuShi
 * File Name:ChineseUtil.java
 * Package Name:com.gc.jzgpinggushi.uitls
 * Date:2014-9-1????10:37:21
 * Copyright (c) 2014, wangyd523@gmail.com All Rights Reserved.
 *
 */
//package com.java2s;
import java.io.UnsupportedEncodingException;

public class Main {

    public static String getFullAscii(String cnStr) {
        if (null == cnStr || "".equals(cnStr.trim())) {
            return cnStr;
        }
        char[] chCnArs = cnStr.toCharArray();
        StringBuffer sbReturn = new StringBuffer();
        for (int i = 0, iLen = chCnArs.length; i < iLen; i++) {
            int iAscii = getCnAscii(chCnArs[i]);
            if (iAscii == 0) {
                sbReturn.append(chCnArs[i]).append(" ");
            } else {
                sbReturn.append((Integer.toHexString(iAscii)).toUpperCase())
                        .append(" ");
            }
        } // end of for
        return sbReturn.toString();
    }

    public static int getCnAscii(char cn) {
        byte[] byteAscii;
        try {
            byteAscii = (String.valueOf(cn)).getBytes("GBK");
        } catch (UnsupportedEncodingException ex) {
            return 0;
        }
        if (byteAscii == null || byteAscii.length > 2
                || byteAscii.length <= 0) {
            return 0;
        }
        if (byteAscii.length == 1) {
            return byteAscii[0];
        }
        if (byteAscii.length == 2) {
            int iHightByte = 256 + byteAscii[0];
            int iLowByte = 256 + byteAscii[1];
            int iAscii = (256 * iHightByte + iLowByte) - 256 * 256;
            return iAscii;
        }
        return 0;
    }
}

Related Tutorials