我需要将字符串转换为十六进制字节数组,我的代码是:

 public static byte[] stringToHex(final String buf)
    {
        return DatatypeConverter.parseHexBinary(buf);
    }


根据java doc将字符串转换为Hex DatatypeConverter使用以下实现

public byte[] parseHexBinary(String s) {
        final int len = s.length();

        // "111" is not a valid hex encoding.
        if (len % 2 != 0) {
            throw new IllegalArgumentException("hexBinary needs to be even-length: " + s);
        }

        byte[] out = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            int h = hexToBin(s.charAt(i));
            int l = hexToBin(s.charAt(i + 1));
            if (h == -1 || l == -1) {
                throw new IllegalArgumentException("contains illegal character for hexBinary: " + s);
            }

            out[i / 2] = (byte) (h * 16 + l);
        }

        return out;
    }


这意味着只有偶数长度的字符串才可以合法转换。但是在php中没有这样的约束
例如php中的代码:

echo pack("H*", "250922f67dcbc2b97184464a91e7f8f");


在java中

String hex = "250922f67dcbc2b97184464a91e7f8f";
        System.out.println(stringToHex(hex));//my method that was described earlier


为什么以下字符串在php中合法?

最佳答案

如果字符数是奇数,PHP只会添加一个最终的0

这两个

echo pack("H*", "48454C50");
echo pack("H*", "48454C5");




HELP

关于java - 将奇数长度的Java字符串转换为十六进制字节数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47985755/

10-12 00:51
查看更多