Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -372,12 +372,19 @@ public static byte[] decodeHex(final String value) {

byte[] bytes = new byte[value.length() / 2];
for (int i = 0; i < value.length(); i += 2) {
bytes[i / 2] = (byte) Integer.parseInt(value.substring(i, i + 2), 16);
bytes[i / 2] = (byte) ((hexToNibble(value.charAt(i)) << 4) | hexToNibble(value.charAt(i + 1)));
}

return bytes;
}

private static int hexToNibble(final char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
throw new NumberFormatException("illegal hexadecimal character " + c + " in hex string");
Comment thread
paulk-asert marked this conversation as resolved.
}

/**
* Calculate md5 of the CharSequence instance
* @return md5 value
Expand Down
13 changes: 13 additions & 0 deletions src/test/groovy/groovy/HexTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ class HexTest {
"1g".decodeHex()
}

// a leading sign is not a valid hexadecimal character and must be rejected
// (Integer.parseInt would otherwise accept it and decode a wrong byte)
["-1", "+a", "-f", "+0"].each { bad ->
shouldFail(NumberFormatException) {
bad.decodeHex()
}
}

// non-ASCII digit characters are not valid hexadecimal either
shouldFail(NumberFormatException) {
"11".decodeHex()
}

// test to make sure a leading zero is handled correctly
bytes = "0a".decodeHex()
assert bytes.length == 1
Expand Down
Loading