Skip to content

Commit 5c56f09

Browse files
author
Eugen
authored
Merge pull request eugenp#783 from sbmaggarwal/master
Added HexToAscii example.
2 parents c48a5c2 + f1d7209 commit 5c56f09

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.hexToAscii;
2+
3+
public class HexToAscii {
4+
5+
@Test
6+
public static void whenHexToAscii() {
7+
8+
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
9+
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
10+
11+
assertEquals(asciiString, hexToAscii(hexEquivalent));
12+
}
13+
14+
@Test
15+
public static void whenAsciiToHex() {
16+
17+
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
18+
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
19+
20+
assertEquals(hexEquivalent, asciiToHex(asciiString));
21+
}
22+
23+
private static String asciiToHex(String asciiStr) {
24+
25+
char[] chars = asciiStr.toCharArray();
26+
StringBuilder hex = new StringBuilder();
27+
for (char ch : chars) {
28+
hex.append(Integer.toHexString((int) ch));
29+
}
30+
31+
return hex.toString();
32+
}
33+
34+
private static String hexToASCII(String hexStr) {
35+
36+
StringBuilder output = new StringBuilder("");
37+
for (int i = 0; i < hexStr.length(); i += 2) {
38+
String str = hexStr.substring(i, i + 2);
39+
output.append((char) Integer.parseInt(str, 16));
40+
}
41+
return output.toString();
42+
}
43+
}

0 commit comments

Comments
 (0)