views:

9725

answers:

7

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 backward?

A: 

XKCD Forum : converting bytes to hexstring

And you got how to go from String to byte[] in previous question

Gandalf
+1  A: 

I would suggest something like this, where str is your input string:

StringBuffer hex = new StringBuffer();
char raw = str.toCharArray();
for (int i=0;i<raw.length;i++) {
    if (raw[i] <= 9)
        hex.append('0');
    hex.append(Integer.toHexString(raw[i]);
}

(Untested, there probably is an issue with multibyte characters here.)


(Edit by Software Monkey)

Code in the loop should be:

    if     (raw[i]<=0x000F) { hex.append("000"); }
    else if(raw[i]<=0x00FF) { hex.append("00" ); }
    else if(raw[i]<=0x0FFF) { hex.append("0"  ); }
    hex.append(Integer.toHexString(raw[i]));

and, personally, I would uppercase the result, as in:

    hex.append(Integer.toHexString(raw[i]).toUpperCase());
rodion
Thank you! The code worked (with some adjustments).
Thanks for the correction, Software Monkey. I was pretty tired when I wrote the answer, and my test for 'raw[i] <= 9' is clearly insufficient.
rodion
+1  A: 

The numbers that you encode into hexadecimal must represent some encoding of the characters, such as UTF-8. So first convert the String to a byte[] representing the string in that encoding, then convert each byte to hexadecimal.

public static String hexadecimal(String input, String charsetName) throws UnsupportedEncodingException {
    if (input == null) throw new NullPointerException();
    return asHex(input.getBytes(charsetName));
}

private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();

public static String asHex(byte[] buf)
{
    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);
}
Stephen Denne
+2  A: 
byte[] bytes = string.getBytes(CHARSET); // you didn't say what charset you wanted
BigInteger bigInt = new BigInteger(bytes);
String hexString = bigInt.toString(16); // 16 is the radix

You could return hexString at this point, with the caveat that leading null-chars will be stripped, and the result will have an odd length if the first byte is less than 16. If you need to handle those cases, you can add some extra code to pad with 0s:

StringBuilder sb = new StringBuilder();
while ((sb.length() + hexString.length()) < (2 * bytes.length)) {
  sb.append("0");
}
sb.append(hexString);
return sb.toString();
Laurence Gonsalves
+4  A: 

Here's a short way to convert it to hex:

public String toHex(String arg) {
    return String.format("%x", new BigInteger(arg.getBytes(/*YOUR_CHARSET?*/)));
}
Kaleb Pederson
A: 

removing as it belonged to diff thread.

ashok gupta
A: 

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?*/)));
}