I am trying to convert a string like \"testing123\" into hexadecimal form in java. I am currently using BlueJ.
And to convert it back, is it the same thing except b
Using Multiple Peoples help from multiple Threads..
I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..
Here's my Encoding & Decoding methods..
// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;
// Text To Hex
public static String textToHex(String text)
{
byte[] buf = null;
buf = text.getBytes(encodingType);
char[] HEX_CHARS = "0123456789abcdef".toCharArray();
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
// Hex To Text
public static String hexToText(String hex)
{
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
String st = new String(data, encodingType);
return st;
}
To ensure that the hex is always 40 characters long, the BigInteger has to be positive:
public String toHex(String arg) {
return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)