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);
}}
string转gb2312Byte16字节串,再转utf-8
于 2023-11-27 16:05:48 首次发布