幾乎不多寫JAVA代碼,第一是確實不會,第二感受JAVA寫起來不爽(較python、golang),但總有萬不得已必需要用java的時候。這裏記錄下使用java實現的hex十六進制和acsii碼之間的轉換(代碼主要仍是從網上找來的,簡單改吧改吧)。html
這裏是將ascii碼轉換爲十六進制值,代碼以下:java
private static String asciiToHex(String asciiStr) { char[] chars = asciiStr.toCharArray(); StringBuilder hex = new StringBuilder(); for (char ch : chars) { hex.append(Integer.toHexString((int) ch)); } return hex.toString(); }
中間使用十進制進行了轉換一下。python
代碼以下:linux
private static String hexToAscii(String hexStr) { StringBuilder output = new StringBuilder(""); for (int i = 0; i < hexStr.length(); i += 2) { String str = hexStr.substring(i, i + 2); output.append((char) Integer.parseInt(str, 16)); } return output.toString(); }
其流程是「Hex<==>Decimal<==>ASCII「。golang
public class StringToHex{ 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(); } public static void main(String[] args) { StringToHex strToHex = new StringToHex(); System.out.println("\n***** Convert ASCII to Hex *****"); String str = "My site is www.361way.com,Fucking Java!"; System.out.println("Original input : " + str); String hex = strToHex.convertStringToHex(str); System.out.println("Hex : " + hex); System.out.println("\n***** Convert Hex to ASCII *****"); System.out.println("Hex : " + hex); System.out.println("ASCII : " + strToHex.convertHexToString(hex)); } }
上面的代碼執行後,輸出以下:app
[root@localhost tmp]# java StringToHex ***** Convert ASCII to Hex ***** Original input : My site is www.361way.com,Fucking Java! Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121 ***** Convert Hex to ASCII ***** Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121 Decimal : 77121321151051161013210511532119119119465154491199712146991111094470117991071051101033274971189733 ASCII : My site is www.361way.com,Fucking Java!
看到上面的示例,是否是想到上面的代碼的一個應用場景 ---- 密碼簡單加密。ui