How convert a data from Hexa to Byte Array

Problem!
Promote the conversion between hex data to byte array and reverse.
Sample:
Hex 30 = 0
Byte[48] = 0

Java                                                 


final protected static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();


private static byte[] toByteArray(String hexString) throws HexStringException
{
   int len = hexString.length();
   byte[] data = new byte[len / 2];
   try 
   { 
      for (int i = 0; i < len; i += 2)
      { 
         data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) +        
           Character.digit(hexString.charAt(i + 1), 16));
      }
   } catch(Exception e)
   { 
      throw new HexStringException(e);
   } 
      return data;
}

private static String fromByteArray(byte[] buffer) 
{
   char[] hexChars = new char[buffer.length * 2];
   for (int j = 0; j < buffer.length; j++)
   {
      int v = buffer[j] & 0xFF;
      hexChars[j * 2] = HEX_ARRAY[v >>> 4];
      hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
   }
   return new String(hexChars);
}







Comentários

Postagens mais visitadas deste blog

How use the LZMA SDK (7Zip)

How config Maven to work with NTLM proxy

Como utilizar a LZMA SDK (7Zip)