String與十六進位制數互轉
阿新 • • 發佈:2018-11-10
/***將字串轉換16進位制**/
public String toHexString(String jsonStr){
byte[] bytes=jsonStr.getBytes();StringBuilder stb=new StringBuilder(bytes.length*2);
//將位元組陣列中每個位元組拆解成2位16進位制整數
for(int i=0;i<bytes.length;i++)
{
stb.append(HEXSTRING.charAt((bytes[i]&0xf0)>>4));
stb.append(HEXSTRING.charAt((bytes[i]&0x0f)>>0));
}
return stb.toString();
}
/*****將16進位制轉換為字串**/
public String toStringHex(String hexStr){
char[] hexs = hexStr.toCharArray();byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++)
{
n = HEXSTRING.indexOf(hexs[2 * i]) * 16;
n += HEXSTRING.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}