网上有一段Unicode转UTF8的,如下所示,我希望寻一段代码像下面将Unicode转成GBK: public static byte[] convertUnicode2UTF8Byte(String s) 

    { 
      byte b[]; 
      byte b1[]; 
      int  len; 
      int  count=0; 
      char c; 
      if(s==null || s.length()==0) 
        return null; 
      len=s.length(); 
      b=new byte[len*3]; 
      for(int i=0;i <len;i++) 
      { 
        c=s.charAt(i); 
        if(0x0080 > c) 
        { 
          b[count++]=(byte)c; 
        } 
        else if(0x0800 > c) 
        { 
          b[count++]=(byte)((c >> 6)| 0xc0); 
          b[count++]=(byte)((c & 0x003F) | 0x80); 
        } 
        else 
        { 
          b[count++]=(byte)((c >> 12) | 0xE0); 
          b[count++]=(byte)(((c & 0x0FC0)>> 6) | 0x80); 
          b[count++]=(byte)((c & 0x003F) | 0x80); 
        } 
      } 
      b1=new byte[count+1]; 
      System.arraycopy(b,0,b1,0,count+1); 
      b=null; 
      return b1; 
    } 
}

解决方案 »

  1.   

    Unicode --> GBK 并不是一一对应靠几个移位就能搞定的,这将编码格式在内部进行转换的。
      

  2.   


    记得有看到介绍,GBK编码的时候为了兼容其他编码,是从别的编码中,整区位移出来的.
      

  3.   

    楼主你要充分利用JAVA已有的编码转换功能啊。
    如:楼主的那个convertUnicode2UTF8Byte是多此一举的,
    用byte[] b=unicodeStr.getBytes("UTF-8");就行了。不知楼主为何要多此一举。[楼主可以比较两者之值]
    另外。将UNICODE串转换成GBK字节数组用:
    byte[] b=unicodeStr.getBytes("GBK");就行了楼主把问题想得复杂了
      

  4.   

    InputStreamReader(inputStream,"utf");
    OuputStreamReader(outputStrea,"gbk");
      

  5.   

    http://www.exampledepot.com/egs/java.nio.charset/ConvertChar.html
    e186. Converting Between Strings (Unicode) and Other Character Set Encodings
      

  6.   

    直接用
    String newstr = new String(oldstr.getBytes("unicode"),"GBK");
    不行吗?
      

  7.   

    字符的GBK码 与 Unicode码 之间,没有律则的映射关系.底层是通过查表完成编解码的.Java 本来有编码处理能力,你要实现的功能,只需str.getBytes("GBK");
      

  8.   

    主要是手机上没有GBK编码,而且我试了好多种中文编码都不行,GB2312、BIG5,我真不知道该怎么办才好。
      

  9.   

    byte[] b=unicodeStr.getBytes("GBK");后面随便转
      

  10.   

     要想详细了解编码与字符集的关系 可以看下http://blog.csdn.net/wekui/archive/2009/11/25/4872872.aspx