如题所示。在写一个通信程序,因对方是UTF-8编码格式,我的信息要编码成UTF-8后,再传给对方。
同时,我收到的信息UTF-8编码格式,要转换成GB2312,再做处理。谢谢。附:
GB2312转换成UTF-8的方法:
public String gbEncoding(String gbString) {
        if (gbString == null)
            return "";
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            if (utfBytes[byteIndex] < 0x80)
                unicodeBytes += utfBytes[byteIndex];
            else {
                String hexB = Integer.toHexString(utfBytes[byteIndex]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes = unicodeBytes + "&#x" + hexB + ";";
            }
        }
        //System.out.println( "unicodeBytes is: " + unicodeBytes );
        return unicodeBytes;
    }
我在网上找到一个东东,不知道怎么用。请大家看看是否可行:
***************************************************
public static String UTF82GB2312(String param)
    {
        try
        {
            param = new String(param.getBytes("ISO8859-1"), "UTF-8");
            byte[] bytes = param.getBytes("UTF-8");
            param = UTF82GB2312(bytes);
            return param;
        }
        catch(Exception e)
        {
            return null;
        }
    }
    
    private static String UTF82GB2312(byte buf[])
    {
        int len = buf.length;
        StringBuffer sb = new StringBuffer(len/2);
        for(int i =0; i<len;i++)
        {
            if(by2int(buf[i])<=0x7F) sb.append((char)buf[i]);
            else if(by2int(buf[i])<=0xDF && by2int(buf[i])>=0xC0)
            {
                int bh = by2int(buf[i] & 0x1F);
                int bl = by2int(buf[++i] & 0x3F);
                bl = by2int(bh << 6 | bl);
                bh = by2int(bh >> 2);
                int c  =  bh<<8 | bl;
                sb.append((char)c);
            }  else if(by2int(buf[i])<=0xEF && by2int(buf[i])>=0xE0){
                int bh = by2int(buf[i] & 0x0F);
                int bl = by2int(buf[++i] & 0x3F);
                int bll = by2int(buf[++i] & 0x3F);
                bh = by2int(bh << 4 | bl>>2);
                bl = by2int(bl << 6 | bll);
                int c  =  bh<<8 | bl;
        //空格转换为半角
        if(c==58865){
            c = 32;
        }
                sb.append((char)c);
            }
        }
        return sb.toString();
    }
***************************************************

解决方案 »

  1.   

    这个问题很好验证,首先,这做一个gb2312的文本,然后处理,看看结果是否是utf-8,文本处理工具建议用emeditor
      

  2.   

    UTF-8可以支持你的GB2312,需要转换吗?
      

  3.   

    因我的对外输出是采用GB2312的,我想应该需要转换?
    原来考虑过这个问题:
    (1)因UTF-8支持GB2312,不需要转换,直接按UTF-8输出就行。
    我们的系统还有其他模块,都是采用GB2312的,设计上不想这个模块按UTF-8输出,这样不统一。(2)如是UTF-8转换到GB2312,因GB2312支持的汉字不多,肯定会抛出例出,也会出现乱码的情况。
    ,现在还是个小工程师,等分析师去想这个问题吧。附:上次贴的还少了一个方法: private static int by2int(int b)
        {
            return b & 0xff;
        }