question: public static byte [ ] hexToBytes ( String str ) { byte [ ] bytes = new byte [ ( str . length ( ) + 1 ) / 2 ] ; if ( str . length ( ) == 0 ) { return bytes ; } bytes [ 0 ] = 0 ; int nibbleIdx = ( str . length ( ) % 2 ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; if ( ! isHex ( c ) ) { throw new IllegalArgumentException ( "string contains non-hex chars" ) ; } if ( ( nibbleIdx % 2 ) == 0 ) { bytes [ nibbleIdx > > 1 ] = ( byte ) ( hexValue ( c ) << 4 ) ; } else { bytes [ nibbleIdx > > 1 ] += ( byte ) hexValue ( c ) ; } nibbleIdx ++ ; } return bytes ; }
target:  Convert a string of hex digits to a byte array, with the first byte in the array being the MSB. The string passed in should be just the raw digits (upper or lower case), with no leading or trailing characters (like '0x' or 'h'). An odd number of characters is supported. If the string is empty, an empty array will be returned. This is significantly faster than using new BigInteger(str, 16).toByteArray(); especially with larger strings. Here are the results of some microbenchmarks done on a P4 2.8GHz 2GB RAM running linux 2.4.22-gg11 and JDK 1.5 with an optimized build: String length        hexToBytes (usec)   BigInteger ----------------------------------------------------- 16                       0.570                 1.43 256                      8.21                 44.4 1024                    32.8                 526 16384                  546                121000