Ticket #8902: bytestohexstring.diff
File bytestohexstring.diff, 2.6 KB (added by , 11 years ago) |
---|
-
src/org/openstreetmap/josm/tools/Utils.java
401 401 return toHexString(byteDigest); 402 402 } 403 403 404 private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 405 404 406 /** 405 407 * Converts a byte array to a string of hexadecimal characters. 406 408 * Preserves leading zeros, so the size of the output string is always twice … … 409 411 * @return hexadecimal representation 410 412 */ 411 413 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 ""; 418 417 } 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 } 419 430 return new String(hexChars); 420 431 } 421 432 -
test/unit/org/openstreetmap/josm/tools/UtilsTest.java
50 50 Assert.assertEquals("ab", Utils.strip(someWhite+"ab"+someWhite)); 51 51 Assert.assertEquals("abc", Utils.strip(someWhite+"abc"+someWhite)); 52 52 } 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 } 53 67 }