KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > inversoft > savant > StringTools


1 /*
2  * Copyright (c) 2003-2004, Inversoft, All Rights Reserved
3  *
4  * This software is distribuable under the GNU Lesser General Public License.
5  * For more information visit gnu.org.
6  */

7 package com.inversoft.savant;
8
9
10 /**
11  * <p>
12  * This is a String toolkit.
13  * </p>
14  *
15  * @author Brian Pontarelli
16  */

17 public class StringTools {
18
19     /**
20      * Converts the contents of the given String from hexidecimal to an array
21      * of bytes. Each character of the String is a single hex value. Therefore,
22      * the the pair of characters equals a single byte. This method is little-endian
23      * (I think).
24      *
25      * @param hexString The hex String to convert
26      * @return An array of bytes
27      */

28     public static byte [] fromHex(String JavaDoc hexString) {
29         int length = hexString.length();
30
31         if ((length & 0x01) != 0) {
32             throw new IllegalArgumentException JavaDoc("odd number of characters.");
33         }
34
35         byte[] out = new byte[length >> 1];
36
37         // two characters form the hex value.
38
for (int i = 0, j = 0; j < length; i++) {
39             int f = Character.digit(hexString.charAt(j++), 16) << 4;
40             f = f | Character.digit(hexString.charAt(j++), 16);
41             out[i] = (byte) (f & 0xFF);
42         }
43
44         return out;
45     }
46 }
Popular Tags