使⽤java实现hex和ascii码的转换
⼏乎很少写JAVA代码,第⼀是确实不会,第⼆感觉JAVA写起来不爽(较python、golang),但总有万不得已必须要⽤java的时候。这⾥记录下使⽤java实现的hex⼗六进制和acsii码之间的转换(代码主要还是从⽹上来的,简单改吧改吧)。
⼀、ASCII to Hex
这⾥是将ascii码转换为⼗六进制值,代码如下:
private static String asciiToHex(String asciiStr) {
char[] chars = CharArray();
StringBuilder hex = new StringBuilder();
for (char ch : chars) {
hex.HexString((int) ch));
}
String();
}
中间使⽤⼗进制进⾏了转换⼀下。
⼆、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));
}
String();
}
其流程是“Hex<==>Decimal<==>ASCII“。
三、完整⽰例
public class StringToHex{
public String convertStringToHex(String str){
char[] chars = CharArray();
StringBuffer hex = new StringBuffer();
for(int i = 0; i < chars.length; i++){
hex.HexString((int)chars[i]));
}
String();
}
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);
python转java代码}
System.out.println("Decimal : " + String());
String();
}
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,Fucking Java!";
System.out.println("Original input : " + str);
String hex = vertStringToHex(str);
System.out.println("Hex : " + hex);
System.out.println("\n***** Convert Hex to ASCII *****");
System.out.println("Hex : " + hex);
System.out.println("ASCII : " + vertHexToString(hex));
}
}
上⾯的代码执⾏后,输出如下:
[root@localhost tmp]# java StringToHex
***** Convert ASCII to Hex *****
Original input : My site is www.361way,Fucking Java!
Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121
***** Convert Hex to ASCII *****
Hex : 4d792073697465206973207777772e3336317761792e636f6d2c4675636b696e67204a61766121
Decimal : 77121321151051161013210511532119119119465154491199712146991111094470117991071051101033274971189733 ASCII : My site is www.361way,Fucking Java!
看到上⾯的⽰例,是不是想到上⾯的代码的⼀个应⽤场景 ---- 密码简单加密。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论