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

独自空忆成欢 提交于 2019-12-11 20:34:54

问题


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.getBytes()));
    }
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).

|improve this question

回答1:


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


来源:https://stackoverflow.com/questions/4787769/how-to-convert-non-printable-character-or-string-to-hex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!