1 package com.openedit.archive.cumulus; 2 3 public class HexToBinaryConverter 4 { 5 public byte[] hexToBinary( String inHex ) 6 { 7 if ( inHex.length() % 2 != 0 ) 8 { 9 throw new IllegalArgumentException ( "Hex string must have an even number of characters" ); 10 } 11 byte[] bytes = new byte[inHex.length() / 2]; 12 for ( int i = 0; i < inHex.length(); i += 2 ) 13 { 14 bytes[i >> 1] = (byte) ( ( convertChar( inHex.charAt( i ) ) << 4 ) | 15 convertChar( inHex.charAt( i + 1 ) ) ); 16 } 17 return bytes; 18 } 19 20 protected int convertChar( char inChar ) 21 { 22 if ( inChar >= '0' && inChar <= '9' ) 23 { 24 return inChar - '0'; 25 } 26 else if ( inChar >= 'A' && inChar <= 'F' ) 27 { 28 return inChar - 'A' + 10; 29 } 30 else 31 { 32 throw new IllegalArgumentException ( "Invalid hex character " + inChar ); 33 } 34 } 35 } 36 | Popular Tags |