62,634
社区成员




byte[] gbkBytes = new String("我").getBytes("GBK");
for (byte b:gbkBytes) System.out.print(Integer.toHexString(b&0x000000ff)+" ");
System.out.println();
byte[] utfBytes = new String(gbkBytes,"GBK").getBytes("UTF-8");
for (byte b:utfBytes) System.out.print(Integer.toHexString(b&0x000000ff)+" ");
System.out.println();
byte[] utfBytes = new String("我").getBytes("UTF-8");
for (byte b:utfBytes) System.out.print(Integer.toHexString(b&0x000000ff)+" ");
System.out.println();
byte[] gbkBytes = new String(utfBytes).getBytes("GBK");
for (byte b:gbkBytes) System.out.print(Integer.toHexString(b&0x000000ff)+" ");
byte[] utfBytes = new byte[100];
....
try {
byte[] gbkBytes = new String(utfBytes).getBytes("GBK");
} catch (UnsupportedEncodingException e) {
}
public static byte[] utfToGBK(byte[] srcByte,String encoding) throws UTFDataFormatException{
StringBuffer str = new StringBuffer();
int len = srcByte.length;
int char1, char2, char3;
int count = 0;
while (count < len) {
char1 = (int) srcByte[count] & 0xff;
switch (char1 >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
count++;
str.append( (char) char1);
break;
case 12:
case 13:
count += 2;
if (count > len) {
throw new UTFDataFormatException();
}
char2 = (int) srcByte[count - 1];
if ( (char2 & 0xC0) != 0x80) {
throw new UTFDataFormatException();
}
str.append( (char) ( ( (char1 & 0x1F) << 6) | (char2 & 0x3F)));
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
count += 3;
if (count > len) {
throw new UTFDataFormatException();
}
char2 = (int) srcByte[count - 2];
char3 = (int) srcByte[count - 1];
if ( ( (char2 & 0xC0) != 0x80) || ( (char3 & 0xC0) != 0x80)) {
throw new UTFDataFormatException();
}
str.append( (char) ( ( (char1 & 0x0F) << 12) |
( (char2 & 0x3F) << 6) |
( (char3 & 0x3F) << 0)));
break;
default:
throw new UTFDataFormatException();
}
}
String temp = new String(str);
try{
if(encoding==null) encoding = "GBK";
return temp.getBytes(encoding);
}catch(Exception e){
return null;
}
}
byte[] returnBytes = Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding("gb2312"), bytes);