请教高手,用java如何将UTF-8字符转成GBK编码格式

liwei007 2008-03-09 12:48:44
以下是用java将GBK字符转成UTF-8编码格式, 那么反过来,如何将UTF-8字符转成GBK编码格式呢?
package com.lang.string;
public class ConverFromGBKToUTF8 {
public static void main(String[] args){
try {
ConverFromGBKToUTF8 convert = new ConverFromGBKToUTF8();
byte [] fullByte = convert.gbk2utf8(chenese);
String fullStr = new String(fullByte, "UTF-8");
System.out.println("string from GBK to UTF-8 byte: " + fullStr);
} catch (Exception e) {
e.printStackTrace();
}
}

public byte[] gbk2utf8(String chenese){
char c[] = chenese.toCharArray();
byte [] fullByte =new byte[3*c.length];
for(int i=0; i<c.length; i++){
int m = (int)c[i];
String word = Integer.toBinaryString(m);
// System.out.println(word);

StringBuffer sb = new StringBuffer();
int len = 16 - word.length();
//补零
for(int j=0; j<len; j++){
sb.append("0");
}
sb.append(word);
sb.insert(0, "1110");
sb.insert(8, "10");
sb.insert(16, "10");

// System.out.println(sb.toString());

String s1 = sb.substring(0, 8);
String s2 = sb.substring(8, 16);
String s3 = sb.substring(16);

byte b0 = Integer.valueOf(s1, 2).byteValue();
byte b1 = Integer.valueOf(s2, 2).byteValue();
byte b2 = Integer.valueOf(s3, 2).byteValue();
byte[] bf = new byte[3];
bf[0] = b0;
fullByte[i*3] = bf[0];
bf[1] = b1;
fullByte[i*3+1] = bf[1];
bf[2] = b2;
fullByte[i*3+2] = bf[2];

}
return fullByte;
}
}

...全文
3063 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiujinlei 2009-02-25
  • 打赏
  • 举报
回复
麻烦下,你写的 GBK转换成UTF-8代码有问题。
你试过没?
你试试转换一个字阿,或是转换“可怜”这个词试试。
谢谢 请教下.....
老紫竹 2008-03-09
  • 打赏
  • 举报
回复
字符串为UTF-8的,可以用
str = new String(str.getByte(),"UTF-8");
转化为Java的unicode格式,然后用
str.getByte("GBK");
转化为"GBK"的字节码

注意,
1 一个页面里,你只能选择一个。
2 java内部只有unicode编码。
liwei007 2008-03-09
  • 打赏
  • 举报
回复
能否不用String fullStr = new String(tempString.getBytes("UTF-8"), "GBK");
也就是不用java自带的转换方式, 自己写一个函数。
  • 打赏
  • 举报
回复
String textcontent=new String(request.getParameter("boy").getBytes("UTF-8")).trim();
String textcontent=new String(request.getParameter("boy").getBytes("GBK")).trim();
zjhlht 2008-03-09
  • 打赏
  • 举报
回复
JVM的编码和解码过程行不行?
hmsuccess 2008-03-09
  • 打赏
  • 举报
回复
也可以现将UTF-8转为unicode ,在转换为gbk
liwei007 2008-03-09
  • 打赏
  • 举报
回复
如何将UTF-8字符转成GBK编码格式呢?
自己先顶一下!!!
hmsuccess 2008-03-09
  • 打赏
  • 举报
回复

try {
String fullStr = new String(tempString.getBytes("UTF-8"), "GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧