字符轉換

toHexString
public static String toHexString(int i)以十六進制的無符號整數形式返回一個整數參數的字符串表示形式。
如果參數爲負,那麼無符號整數值爲參數加上 232;否則等於該參數。將該值轉換爲十六進制(基數 16)的無前導 0 的 ASCII 數字字符串。如果無符號數的大小值爲零,則用一個零字符 '0' (’/u0030’) 表示它;否則,無符號數大小的表示形式中的第一個字符將不是零字符。用以下字符作爲十六進制數字:

0123456789abcdef
這些字符的範圍是從 '/u0030' 到 '/u0039' 和從 '/u0061' 到 '/u0066'。如果希望得到大寫字母,可以在結果上調用 String.toUpperCase() 方法:
Integer.toHexString(n).toUpperCase()

參數:
i - 要轉換成字符串的整數。
返回:
用十六進制(基數 16)參數表示的無符號整數值的字符串表示形式。
// 轉化字符串爲十六進制編碼
public static String toHexString(String s)  
{  
String str="";  
for (int i=0;i<s.length();i++)  
{  
int ch = (int)s.charAt(i);  
String s4 = Integer.toHexString(ch);  
str = str + s4;
}  
return str;  
}

// 轉化十六進制編碼爲字符串
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
   for(int i = 0; i < baKeyword.length; i++)
   {
    try
    {
    baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
   }
 
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}

// 轉化十六進制編碼爲字符串
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
   for(int i = 0; i < baKeyword.length; i++)
   {
    try
    {
    baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
   }
 
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}

public static void main(String[] args) {
System.out.println(encode("中文"));
System.out.println(decode(encode("中文")));
}
/*
* 16進制數字字符集
*/
private static String hexString="0123456789ABCDEF";
/*
* 將字符串編碼成16進制數字,適用於所有字符(包括中文)
*/
public static String encode(String str)
{
//根據默認編碼獲取字節數組
byte[] bytes=str.getBytes();
StringBuilder sb=new StringBuilder(bytes.length*2);
//將字節數組中每個字節拆解成2位16進制整數
for(int i=0;i<bytes.length;i++)
{
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
}
return sb.toString();
}
/*
* 將16進制數字解碼成字符串,適用於所有字符(包括中文)
*/
public static String decode(String bytes)
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
//將每2位16進制整數組裝成一個字節
for(int i=0;i<bytes.length();i+=2)
baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
return new String(baos.toByteArray());
}

發佈了83 篇原創文章 · 獲贊 26 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章