String s="汉字";
char ch=s.charAt(0);
得到的ch是Unicode编码吧,如何把它转换成GB的编码?

解决方案 »

  1.   


    package csdn;import java.io.UnsupportedEncodingException;public class toGBK {
    public static void main(String[] args) {
    try {
    String str = "汉字";
    byte[] b = str.getBytes();
    String toGBK = new String(b, "GBK");
    System.out.println(toGBK);
    } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
      

  2.   

    ByteBuffer encoded = Charset.forName("GBK").encode("汉字");
      

  3.   


    String s=URLEncoder.encode("中文", "UTF-8")URLEncoder.decode((s,"UTF-8")
      

  4.   

    在windows 环境下,
    String str = "汉字";
      byte ch=str.getBytes()[0]; //它就是‘汉'的GBK第一个内码-70(0xba),同理str.getBytes()[1]...
    其它环境未测试,但你可以这样:
      public static void main(String[] args) {
        
         // TODO, add your application code
           String str = "汉字";
           String s=null;
           try {
             s=new String(str.getBytes("GBK"));
             
           }
            catch(Exception e) {
               System.out.println(e);
            
             }
             
           byte[] ch=s.getBytes();
           for(int i=0;i<4;i++)
         System.out.println(ch[i]);
        }
    结果为
    -70
    -70
    -41
    -42
    正对应“汉字”的GBK内码
    BA BA D7 D6  
      

  5.   

    完整的代码:public class getgbk {
        
        public static void main(String[] args) {
        
         // TODO, add your application code
           String str = "汉字";
           String s=null;
           try {
             s=new String(str.getBytes("GBK"));
             
           }
            catch(Exception e) {
               System.out.println(e);
            
             }
             
           byte[] b=s.getBytes();
           
           for (int i = 0; i < b.length; i++) { 
                 String hex = Integer.toHexString(b[i] & 0xFF); 
                 if (hex.length() == 1) { 
                   hex = '0' + hex; 
             } 
         System.out.print(hex.toUpperCase() ); 
       } 
           结果为
    BABAD7D6
      

  6.   

    to : lijielove520
    GB 就是国(家)标(准),汉字编码最早的为GB2312-80
    to:楼主
      我的代码在cygwin(UTF-8)环境下测试没问题
      但必须用s=new String(str.getBytes("GBK"));转换
      

  7.   

            String s = "汉字";
            StringBuilder rs = new StringBuilder();
            byte[] encoded = Charset.forName("GBK").encode(s).array();
            for(byte b : encoded){ rs.append(String.format("%X", b & 0xff));}
            System.out.println(rs.toString());