编码在解码逆着顺序就可以了吗?
编码的程序是
String tempS = new String(resutlBytesData[p], "UTF-16BE");//得到的tempS就是乱码了
byte[] btmp = tempS.getBytes("GBK");
System.out.println(Base64.encode(btmp));
然后我解码的顺序是
byte[] b1 = Base64.decode(s1);
String ss1 = new String(b1,"GBK");
byte[] bb1 = ss1.getBytes("UTF-16BE");
bb1解出来后是resutlBytesData[p],但是不对?哪里出错了吗? 编码 乱码
[解决办法]
问题是你输入的那些bytes是怎么来的?
我不明白你想实现什么:
下面是我的一个字符转为字节数组 转为16进制字符 然后转回的例子。:
public static void main(String[] args) {
String str = hexString("好啊tianta了");
System.out.println(str);
byte[] b = HexString2Bytes(str);
try {
String s=new String(b,"GB2312");
System.out.println(s);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String hexString(String str) {
String ret = "";
byte[] b;
try {
b = str.getBytes("GB2312");
for (int i = b.length - 1; i >= 0; i--) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ret;
}
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = b.length-1; i >=0; i--) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4)
[解决办法]
parse(c1));
}
return b;
}
private final static byte[] hex = "0123456789ABCDEF".getBytes();
private static int parse(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}