1

I need to convert string to hexademical byte array,my code is:

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

According to java doc to convert string to Hex DatatypeConverteruse the following implementation

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;
    }

It means that only strings with the even length is legal to be converted.But in php there is no such constraint For example code in php:

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

And in java

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

Why the following string is legal in php?

5
  • One language is more lenient than the other. What's your question exactly? Commented Dec 27, 2017 at 2:54
  • Probably because PHP simply treats the final character as a number between 0 and 15 and not 0 through 255. Commented Dec 27, 2017 at 2:54
  • @vandench More likely the first character. But I'm just guessing. Commented Dec 27, 2017 at 2:54
  • @vandench According to this comment, we're both wrong. Leave it to PHP to find the most unintuitive interpretation. Commented Dec 27, 2017 at 2:56
  • @shmosel :/ This is called laziness and not you you should pad hex strings. Commented Dec 27, 2017 at 3:00

1 Answer 1

2

PHP just adds a final 0 in case the number of characters is odd.

Both of these

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

yield

HELP
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.