碰到一個比較怪異的問題,byte陣列格式的16進制數,如果轉換為String型別,再通過String型別獲取到byte陣列格式,發現原來的資料會發生改變,而且還和源byte陣列的資料是相關的,代碼如下,如果getBytes里的bytes是{(byte)0xFB, (byte)0x0A},那么執行后列印的是8431A4370A,如果bytes是{(byte)0xFB, (byte)0x4A},那么執行后列印出來的是原資料FB4A。求教!
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class MainApp {
private static String hexToString(byte[] hexs) {
if(hexs == null || hexs.length <= 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for(byte hex : hexs) {
int ch = (int)((hex & 0xF0) >> 4);
String s = Integer.toHexString(ch);
sb.append(s);
ch = (int)(hex & 0x0F);
s = Integer.toHexString(ch);
sb.append(s);
}
return sb.toString().toUpperCase();
}
private static byte[] getBytes() {
byte[] bytes = {(byte)0xFB, (byte)0x4A};
return bytes;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String str = new String(getBytes(), "GB18030");
System.out.println(hexToString(str.getBytes("GB18030")));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/170161.html
標籤:Java相關
