日期:2014-05-20  浏览次数:20650 次

Java字符串的GBK编码程序问题
/*中国两个字符串的GBK编码为“D6D0B9FA”,
在下面程序(1)与(2)处应该怎样写
           才能打印出中国*/
   求高手帮忙解决此问题


	public static void main(String[] args) throws UnsupportedEncodingException{


/*中国两个字符串的GBK编码“D6D0B9FA”,
怎样拼接出中国*/
char[] num={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
String code="中国";
byte[] bytes=code.getBytes("GBK");
  
StringBuffer buf=new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
byte b=bytes[i];
byte r=(1);
byte h=(2);
buf.append(num[h]);
buf.append(num[r]);
}
System.out.println("==汉字===="+buf);

}
编码 java stringbuffer GBK编码

------解决方案--------------------

/**
 * 获取字符串的不同字符集的编码字符串
 * @param data
 * @return
 */
public static String getBytes(byte[] data) {
String str = "";
    for (byte b : data) {
        str = str + "0x" + toHexString(b) + " ";
    }
    return str;
}

public static String toHexString(byte value) {
    String tmp = Integer.toHexString(value & 0xFF);
    if (tmp.length() == 1) {
        tmp = "0" + tmp;
    }
    return tmp.toUpperCase();
}

public static void main(String[] args) {
    String str = "中国";
    System.out.println(getBytes(str.getBytes(Charset.forName("unicode"))));
    System.out.println(getBytes(str.getBytes(Charset.forName("GBK"))));
    System.out.println(getBytes(str.getBytes(Charset.forName("UTF-8"))));
    byte[] bytes = new byte[]{(byte) 0xE4, (byte) 0xB8, (byte) 0xAD, (byte) 0xE5, (byte) 0x9B, (byte) 0xBD};
    try {
System.out.println(new String(bytes, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}