开发者

How to convert non-printable character or string to hex?

I have String which contain the next hex presentation: "5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9"

You understand that this is just hex and I need to get this hex presentation from String. String looks like: "ED>@@2.W.W'KJ%z_{T g"

So, how to get from "ED>@@2.W.W'KJ%z_{T g" hex presentation "5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9"? This is unprintable characters so I can't use this:

    public static String stringToHex(String arg) {
        return String.format("%x", new BigInteger(arg.ge开发者_运维问答tBytes()));
    }
result: -10404282104042104042104042104042104042c7eea21040428189104042104042f5. And also this returns me something strange:
System.out.println(String.format("%h", Integer.toHexString(buff.charAt(0))));
result: 6d1.

And this code sometimes works. The data comes from socket (as String because I need to get many answers as String and only this Auth Challenge as hex).


This is the correct solution:

public static String toHexString(byte[] bytes) {  
    StringBuilder out = new StringBuilder();
    for (byte b: bytes) {
        out.append(String.format("%02X", b) + " ");
    }
    return out.toString();
}

Solution with Integer.toHexString() is wrong for the following reasons:

  1. It doesn't add leading zero to bytes 0x01 - 0x0F
  2. It prints bytes 0x80 - 0xFF as negative integers in 2's complement representation
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜