几乎很少写JAVA代码,第一是确实不会,第二感觉JAVA写起来不爽(较python、golang),但总有万不得已必须要用java的时候。这里记录下使用java实现的hex十六进制和acsii码之间的转换(代码主要还是从网上找来的,简单改吧改吧)。

一、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 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));
}
}

上面的代码执行后,输出如下:

[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!

看到上面的示例,是不是想到上面的代码的一个应用场景 ---- 密码简单加密。

原文来自:http://www.361way.com/convert-hex-to-ascii/5870.html

本文地址:https://www.linuxprobe.com/java-hex-asci.html编辑:张雄,审核员:逄增宝