Java怎么将字符串转换为GB2312原编码

如题:例 String a = "青白";转换为 青(c7e0)白( b0d7) ,c7e0为GB2312编码。

@Test
public void test333(){
String a="青白";
try {
byte[] b=a.getBytes("GB2312");
System.out.println(bytesToHexFun1(b));
 
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//将byte数组转成16进制字符串
 public static String bytesToHexFun1(byte[] bytes) {
    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);
    }
    
中心思想就是先转成GB2312的byte数组,再转成16进制就可以了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-07-25
在java中,字符默认存储的编码为utf-8码。
所以在转码的时候,首先byte[] sour = .getBytes("utf-8"),获取正确的byte数组。
再通过String dest = new String(sour , "gb2312");获取按gb2312编码的字符串。
第2个回答  2014-08-27
方法一:
思路:先转为Unicode,然后转为GBK
String utf8 = new String(t.getBytes( "UTF-8"));  
System.out.println(utf8);  
String unicode = new String(utf8.getBytes(),"UTF-8"); 
System.out.println(unicode);
String gbk = new String(unicode.getBytes("GBK")); 
System.out.println(gbk);    
方法二:
public static void main(String[] args) {
        String str="字符串编码转换";
        try {
          byte[] temp=str.getBytes("utf-8");//这里写原编码方式
            byte[] newtemp=new String(temp,"utf-8").getBytes("gbk");//这里写转换后的编码方式
            String newStr=new String(newtemp,"gbk");//这里写转换后的编码方式
            System.out.println(newStr);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

追问

追答

回家啦

本回答被网友采纳
第3个回答  2014-08-27
+string
。。。。。。追问

什么意思?

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网