前言:
此刻咱们对“java16进制”大致比较关心,姐妹们都需要知道一些“java16进制”的相关知识。那么小编同时在网上收集了一些关于“java16进制””的相关知识,希望各位老铁们能喜欢,我们一起来了解一下吧!一、ASCII to Hex
这里是将ascii码转换为十六进制值,代码如下:
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();}
中间使用十进制进行了转换一下。
二、hex to ascii
代码如下:
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“。
三、完整示例
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 pairsString output = hex.substring(i, (i + 2));//convert hex to decimalint decimal = Integer.parseInt(output, 16);//convert the decimal to charactersb.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 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));}}
上面的代码执行后,输出如下:
[root@localhost tmp]# java StringToHex***** Convert ASCII to Hex *****Original input : My site is Java!Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121***** Convert Hex to ASCII *****Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121Decimal : 77121321151051161013210511532119119119465154491199712146991111094470117991071051101033274971189733ASCII : My site is Java!
看到上面的示例,是不是想到上面的代码的一个应用场景 ---- 密码简单加密。
标签: #java16进制