Java中文转GBK码



遇到一个需求,一个接口的调用时,需要将中文转成对应的GBK码,然后发请求调用,大概搜了下,貌似没有简单可行的现成方法,不像python能够直接decode / encode。

找的时候有一个帖子给了启示: java默认用Unicode存储String,所以直接转成某种编码的byte的同时,就已经转成了该编码的encoding。

于是找了个例子,

天安门 对应的gbk码是: 

%CC%EC%B0%B2%C3%C5

于是转一下

byte[] bytes = source.getBytes("GBK");

再计算下补码(还是反码)神马的。

for(byte b : bytes) {
sb.append("%" + Integer.toHexString((b & 0xff)).toUpperCase());
}

就得到了上述的CC EC B0 B2 C3 C5

按照格式塞进去百分号,大功告成。完整的函数如下:

 

public static String toGBK(String source) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = source.getBytes("GBK");
        for(byte b : bytes) {
            sb.append("%" + Integer.toHexString((b & 0xff)).toUpperCase());
        }
        
        return sb.toString();
    }


补:


public class Tranform {
	public static void main(String args[]) throws Exception {
        String chineseStr="我们";
        Transform t=new Transform();
        System.out.println(t.Chinese2UTF_8(chineseStr));
        System.out.println(t.Chinese2GBK(chineseStr));
        System.out.println(t.GBK2Chinese(t.Chinese2GBK(chineseStr)));
	}
}

 class Transform {
  //中文转换成UTF-8编码(16进制字符串),每个汉字3个字节
  public String Chinese2UTF_8(String chineseStr)throws Exception {
	StringBuffer utf8Str = new StringBuffer();
	byte[] utf8Decode = chineseStr.getBytes("utf-8");
	for (byte b : utf8Decode) 
		utf8Str.append(Integer.toHexString(b&0xFF));
	return utf8Str.toString().toUpperCase();
  }	
	
  //中文转换成GBK码(16进制字符串),每个汉字2个字节
  public String Chinese2GBK(String chineseStr)throws Exception {
	StringBuffer GBKStr = new StringBuffer();
	byte[] GBKDecode = chineseStr.getBytes("gbk");
	for (byte b : GBKDecode) 
		GBKStr.append(Integer.toHexString(b&0xFF));
	return GBKStr.toString().toUpperCase();
	}
	
	
  //16进制GBK字符串转换成中文
  public String GBK2Chinese(String GBKStr)throws Exception{
	byte[] b = HexString2Bytes(GBKStr);
	String chineseStr = new String(b, "gbk");//输入参数为字节数组
	return chineseStr;
   }
  
  //把16进制字符串转换成字节数组
  public byte[] HexString2Bytes(String hexStr) {
	 byte[] b = new byte[hexStr.length() / 2];
	 for (int i = 0; i < b.length; i++) 
       b[i]=(byte) Integer.parseInt(hexStr.substring(2*i,2*i+2),16);
	return b;
  }

	
   //把字节数组转换成16进制字符串
   public static final String bytesToHexString(byte[] byteArray){
	 StringBuffer hexStr = new StringBuffer(byteArray.length*2);
	 for (int i = 0; i < byteArray.length; i++) {
		 String sTemp= Integer.toHexString(0xFF& byteArray[i]);
		 int j=0;
	     while(j<2-sTemp.length())
	    	 {sTemp="0"+sTemp;j++;}
	     hexStr.append(sTemp.toUpperCase());
	   }
	  return hexStr.toString();
	}

 }


猜你喜欢

转载自blog.csdn.net/u011702993/article/details/78318429