java GBK与UTF-8的转换

本文介绍了一个Java程序,该程序能够将GB编码的字符串转换为UTF-8编码。通过解析并重新构造二进制数据,实现了不同字符集间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码如下:

import java.io.UnsupportedEncodingException;


public class CharsetConvertor {

public static void main(String[] args){
   // test a method getHexString(byte b)
//   System.out.println(getHexString((byte)256));
   //test a method getBinaryString(int i)
//   System.out.println(getBinaryString(8));
  
   try {
    System.out.println(gbToUtf8("经"));
   
   
   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

public static String gbToUtf8(String source) throws UnsupportedEncodingException{
   StringBuffer sb = new StringBuffer();
   for(int i=0; i<source.length(); i++){
    String s = source.substring(i, i+1);
    if(s.charAt(0)>0x80){
     byte[] bytes = s.getBytes("Unicode");
     String binaryStr = "";
     for(int j=2;j<bytes.length;j+=2){
      //the first byte
      String hexStr = getHexString(bytes[j+1]);
      String binStr = getBinaryString(Integer.valueOf(hexStr, 16));
      binaryStr += binStr;
     
      //the second byte
      hexStr = getHexString(bytes[j]);
      binStr = getBinaryString(Integer.valueOf(hexStr, 16));
     
      binaryStr += binStr;
     }
    
     String s1 = "1110"+binaryStr.substring(0, 4);
     String s2 = "10"+binaryStr.substring(4, 10);
     String s3 = "10"+binaryStr.substring(10, 16);
    
     byte[] bs = new byte[3];
     bs[0] = Integer.valueOf(s1,2).byteValue();
     bs[1] = Integer.valueOf(s2,2).byteValue();
     bs[2] = Integer.valueOf(s3,2).byteValue();
    
     String ss = new String(bs,"UTF-8");
     sb.append(ss);
    }
   }
   return sb.toString();
}

public static String getHexString(byte b){
   String hexStr = Integer.toHexString(b);
   int m = hexStr.length();
   if(m<2){
    hexStr = "0"+hexStr;
   }else{
    hexStr = hexStr.substring(m-2);
   }
   return hexStr;
}

private static String getBinaryString(int i){
   String binaryStr = Integer.toBinaryString(i);
   int length = binaryStr.length();
   for(int k=0; k < 8-length;k++){
    binaryStr = "0"+binaryStr;
   }
   return binaryStr;
}
}

转载于:https://www.cnblogs.com/xinzhuangzi/archive/2010/07/30/4100568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值