Ticket #8902: bytestohexstring.diff

File bytestohexstring.diff, 2.6 KB (added by shinigami, 11 years ago)

byte[] to hex string change + small test

  • src/org/openstreetmap/josm/tools/Utils.java

     
    401401        return toHexString(byteDigest);
    402402    }
    403403
     404    private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
     405
    404406    /**
    405407     * Converts a byte array to a string of hexadecimal characters.
    406408     * Preserves leading zeros, so the size of the output string is always twice
     
    409411     * @return hexadecimal representation
    410412     */
    411413    public static String toHexString(byte[] bytes) {
    412         char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    413         char[] hexChars = new char[bytes.length * 2];
    414         for (int j=0; j<bytes.length; j++) {
    415             int v = bytes[j] & 0xFF;
    416             hexChars[j*2] = hexArray[v/16];
    417             hexChars[j*2 + 1] = hexArray[v%16];
     414
     415        if (bytes == null){
     416            return "";
    418417        }
     418
     419        final int len = bytes.length;
     420        if (len == 0){
     421            return "";
     422        }
     423
     424        char[] hexChars = new char[len * 2];
     425        for (int i = 0, j = 0; i < len; i++) {
     426            final int v = bytes[i];
     427            hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
     428            hexChars[j++] = HEX_ARRAY[v & 0xf];
     429        }
    419430        return new String(hexChars);
    420431    }
    421432
  • test/unit/org/openstreetmap/josm/tools/UtilsTest.java

     
    5050        Assert.assertEquals("ab", Utils.strip(someWhite+"ab"+someWhite));
    5151        Assert.assertEquals("abc", Utils.strip(someWhite+"abc"+someWhite));
    5252    }
     53
     54    /**
     55     * Test of {@link Utils#toHexString} method.
     56     */
     57    @Test
     58    public void testToHexString(){
     59        Assert.assertEquals("", Utils.toHexString(null));
     60        Assert.assertEquals("", Utils.toHexString(new byte[0]));
     61        Assert.assertEquals("01", Utils.toHexString(new byte[]{0x1}));
     62        Assert.assertEquals("0102", Utils.toHexString(new byte[]{0x1,0x2}));
     63        Assert.assertEquals("12", Utils.toHexString(new byte[]{0x12}));
     64        Assert.assertEquals("127f", Utils.toHexString(new byte[]{0x12, 0x7f}));
     65        Assert.assertEquals("fedc", Utils.toHexString(new byte[]{(byte) 0xfe, (byte) 0xdc}));
     66    }
    5367}