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;
}

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 ; }
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
