public static byte [ ] hexToBin ( String hex , int start ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "hexToBin" , new Object [ ] { hex , Integer . valueOf ( start ) } ) ; int digit1 , digit2 ; int length = ( hex . length ( ) - start ) ; // no of characters to be processed // Handle the special case when there is no data if ( length == 0 ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "hexToBin" ) ; return new byte [ 0 ] ; } // It's an error if we have an odd number of hex characters if ( ( length < 0 ) || ( ( length % 2 ) != 0 ) ) { String nlsMsg = nls . getFormattedMessage ( "BAD_HEX_STRING_CWSIU0200" , new Object [ ] { hex } , "The hexadecimal string " + hex + " is incorrectly formatted." ) ; IllegalArgumentException e = new IllegalArgumentException ( nlsMsg ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "hexToBin" , e ) ; throw e ; } // Change length from number of characters to number of bytes to be produced length /= 2 ; // Allocate a buffer to hold the result byte [ ] retval = new byte [ length ] ; // Convert from HexString to a byte array for ( int i = 0 ; i < length ; i ++ ) { digit1 = ( Character . digit ( hex . charAt ( 2 * i + start ) , 16 ) ) << 4 ; digit2 = Character . digit ( hex . charAt ( 2 * i + start + 1 ) , 16 ) ; // The Character.digit() method signals an error by returning -1, so we have // to test for it here if ( ( digit1 < 0 ) || ( digit2 < 0 ) ) { String nlsMsg = nls . getFormattedMessage ( "BAD_HEX_STRING_CWSIF0200" , new Object [ ] { hex } , "The hexadecimal string " + hex + " is incorrectly formatted." ) ; IllegalArgumentException e = new IllegalArgumentException ( nlsMsg ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "hexToBin" , e ) ; throw e ; } retval [ i ] = ( byte ) ( digit1 + digit2 ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "hexToBin" ) ; return retval ; }
Converts a hex string into a byte array holding the binary value . This code is reused from MA88 .