string转gb2312Byte16字节串,再转utf-8


public class GB2312ToUtf8 {

/**
* stringToGB2312 byte16字节串
* @param values
* @return
*/

public static String GB2312ToUtf8(String values) throws UnsupportedEncodingException {
        String utf8 = null;
        String gbToUt = null;
        byte[] baKeyword = new byte[values.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
                try {
                        baKeyword[i] = (byte) (0xff & Integer.parseInt(values.substring(
                        i * 2, i * 2 + 2), 16));
                } catch (Exception e) {
                        e.printStackTrace();
                }
         }
         try {
                gbToUt = new String(baKeyword, "GB2312");
        } catch (Exception e1) {
                e1.printStackTrace();
        }
        utf8 = new String(gbToUt.getBytes(), "utf-8");
        return utf8;
}

/**
* stringToGB2312 byte16字节串
* @param values
* @return
*/
public static String stringToGB2312(String values) {
        if(values == null){
                return null;
        }
        try {
                byte[] bytes=values.getBytes("GB2312");
                char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
                        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
                // 一个byte为8位,可用两个十六进制位标识
                char[] buf = new char[bytes.length * 2];
                int a = 0;
                int index = 0;
                // 使用除与取余进行转换
                for(byte b : bytes) {
                        if(b < 0) {
                               a = 256 + b;
                        } else {
                                a = b;
                        }
                        buf[index++] = HEX_CHAR[a / 16];
                        buf[index++] = HEX_CHAR[a % 16];
                }
                return new String(buf);
          } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
        }
                return null;
}

/**
* 测试
* @return
*/
public static void main(String[] args) throws UnsupportedEncodingException {
        String a = "50";
        String gb2312Byte16 = GB2312ToUtf8.stringToGB2312(a);
        System.out.println(gb2312Byte16);
        String utf8 = GB2312ToUtf8.GB2312ToUtf8(gb2312Byte16);
        System.out.println(utf8);

        String b = "中国,中国,ed,123";
        String gb2312Byte161 = GB2312ToUtf8.stringToGB2312(b);
        System.out.println(gb2312Byte161);
        String utf81 = GB2312ToUtf8.GB2312ToUtf8(gb2312Byte161);
        System.out.println(utf81);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值