To convert String to Hexadecimal i am using:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}
This is outlined in the top-voted answer here: Converting A String To Hexadecimal In Java
How do i do the reverse ie Hexadecimal to String?
You can reconstruct bytes[]
from the converted string, here's one way to do it:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return new String(bytes);
}
Another way is using DatatypeConverter
, from javax.xml.bind
package:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = DatatypeConverter.parseHexBinary(hex);
return new String(bytes, "UTF-8");
}
Unit tests to verify:
@Test
public void test() throws UnsupportedEncodingException {
String[] samples = {
"hello",
"all your base now belongs to us, welcome our machine overlords"
};
for (String sample : samples) {
assertEquals(sample, fromHex(toHex(sample)));
}
}
Note: the stripping of leading 00
in fromHex
is only necessary because of the "%040x"
padding in your toHex
method. If you don't mind replacing that with a simple %x
, then you could drop this line in fromHex
:
hex = hex.replaceAll("^(00)+", "");
String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));
output:
0000000000000000000000000000000000616263
abc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.