问题

我试图在java中将像"testing123"这样的字符串转换为十六进制格式。我目前正在使用BlueJ。

把它转换回来,除了落后之外它是一回事吗?


#1 热门回答(172 赞)

这是将其转换为十六进制的简短方法:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}

#2 热门回答(60 赞)

为确保十六进制长度始终为40个字符,BigInteger必须为正数:

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

#3 热门回答(36 赞)

import org.apache.commons.codec.binary.Hex;
...

String hexString = Hex.encodeHexString(myString.getBytes(/* charset */));

http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html


原文链接