java UTF8ToGB2312

方便以后直接使用

    public String UTF8ToGB2312(String str){

        String utf8 = null;
        String gb2312 = null;
        String unicode = null;
        StringBuffer result = new StringBuffer();

        try {
                utf8 = new String(str.getBytes( "UTF-8"));  
                Log.d(TAG, "String utf8 =" + utf8);  
                unicode = new String(utf8.getBytes(),"UTF-8");   
                Log.d(TAG, "String unicode =" + unicode);  
                gb2312 = new String(unicode.getBytes("GB2312"));  
                Log.d(TAG, "String gb2312 =" + gb2312);  
            }
        catch(Exception e){}

        try {
        byte[] bytes = unicode.getBytes("gb2312");
        int length = unicode.getBytes("gb2312").length;

            Log.d(TAG, "length="+length);
            for(int i=0; i<length; i++){
                Log.d(TAG, "bytes["+i+"]="+bytes[i]);
                //int data = (buffer[i] >= 0) ? buffer[i] : (256+buffer[i]);
                String hex = Integer.toHexString(bytes[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = "0" + hex;
                }
                result.append(hex.toUpperCase());
            }
        } catch (Exception e) {}

        Log.d(TAG, "result.toString()="+result.toString()); 
        return result.toString();
    }

猜你喜欢

转载自blog.csdn.net/mingchong2005/article/details/78733207