2012-08-03 25 views
2

我想在我的android應用程序中實現某些功能。我需要在我的類中創建一個字符串變量的HEX表示並將其轉換爲字節數組。事情是這樣的:Android Java創建十六進制字符串並將其轉換爲字節數組並返回

String hardcodedStr = "SimpleText"; 
String hexStr = someFuncForConvert2HEX(hardcodedStr); // this should be the HEX string 
byte[] hexStr2BArray = hexStr.getBytes(); 

之後,我希望能夠以這個hexStr2BArray轉換爲字符串,並得到它的價值。這樣的事情:

String hexStr = new String(hexStr2BArray, "UTF-8"); 
String firstStr = someFuncConvertHEX2Str(hexStr); // the result must be : "SimpleText" 

任何建議/意見我怎麼能做到這一點。另一件事,我應該能夠轉換這個hexString,並在任何其他平臺上獲得它的實際價值...如Windows,Mac,IOS。

+0

你真的需要它是十六進制(字符0..9和a..f),爲什麼字節數組只能是UTF-8編碼的字符串? – 2012-08-03 14:05:46

+0

這是爲了某種安全問題。我必須先將它轉換爲十六進制 – hardartcore 2012-08-03 14:06:53

+0

[將字符串轉換爲十六進制的Java](http://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java)<---> [將十六進制轉換爲ASCII in Java](http://www.mkyong.com/java/how-to-convert-hex-to-ascii-in-java/) – FoamyGuy 2012-08-03 14:22:27

回答

3

以下是我使用的兩個函數,感謝Tim的評論。希望它有助於任何需要它的人。

public String convertStringToHex(String str){ 

    char[] chars = str.toCharArray(); 

    StringBuffer hex = new StringBuffer(); 
    for(int i = 0; i < chars.length; i++){ 
    hex.append(Integer.toHexString((int)chars[i])); 
    } 

    return hex.toString(); 
} 

public String convertHexToString(String hex){ 

    StringBuilder sb = new StringBuilder(); 
    StringBuilder temp = new StringBuilder(); 

    //49204c6f7665204a617661 split into two characters 49, 20, 4c... 
    for(int i=0; i<hex.length()-1; i+=2){ 

     //grab the hex in pairs 
     String output = hex.substring(i, (i + 2)); 
     //convert hex to decimal 
     int decimal = Integer.parseInt(output, 16); 
     //convert the decimal to character 
     sb.append((char)decimal); 

     temp.append(decimal); 
    } 
    System.out.println("Decimal : " + temp.toString()); 

    return sb.toString(); 
} 
相關問題