You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@mina.apache.org by "nullpointer (JIRA)" <ji...@apache.org> on 2015/03/16 21:07:38 UTC

[jira] [Created] (DIRMINA-1008) fromHexString converts non-hex Strings to ByteBuffer

nullpointer created DIRMINA-1008:
------------------------------------

             Summary: fromHexString converts non-hex Strings to ByteBuffer
                 Key: DIRMINA-1008
                 URL: https://issues.apache.org/jira/browse/DIRMINA-1008
             Project: MINA
          Issue Type: Bug
          Components: Core
            Reporter: nullpointer


I came across this by accident in class org.apache.mina.util.ByteBufferDumper:
[fromHexString|https://git-wip-us.apache.org/repos/asf?p=mina.git;a=blob;f=core/src/main/java/org/apache/mina/util/ByteBufferDumper.java;h=e351a139a4a13a2028f55898716e19f21a33a4d4;hb=HEAD#l138] happily converts Strings like "ff, fa, f2" and "not a hex string" to bytes.

Here is a suggestion for curing the problem:
{code}
  public static ByteBuffer fromHexString(final String hex) {
    if (null == hex) {
      throw new IllegalArgumentException(
              "null argument not permitted");
    } else if (hex.length() % 2 != 0) {
      throw new IllegalArgumentException(
              "the hexadecimal string length cannot be odd");
    }
    int size = hex.length() / 2;
    ByteBuffer res = ByteBuffer.allocate(size);

    for (int i = 0; i < hex.length(); i += 2) {
      int b = Integer.parseInt(hex.substring(i, i + 2), 16);
      if (Integer.highestOneBit(b) == 128) {
        b = b - 256;
      }
      res.put((byte) b);
    }

    res.flip();
    return res;
 }
{code}











--
This message was sent by Atlassian JIRA
(v6.3.4#6332)