001package com.hfg.util;
002
003import java.util.regex.Pattern;
004
005//------------------------------------------------------------------------------
006/**
007 * General hexadecimal utility functions.
008 *
009 * @author J. Alex Taylor, hairyfatguy.com
010 */
011//------------------------------------------------------------------------------
012// com.hfg XML/HTML Coding Library
013//
014// This library is free software; you can redistribute it and/or
015// modify it under the terms of the GNU Lesser General Public
016// License as published by the Free Software Foundation; either
017// version 2.1 of the License, or (at your option) any later version.
018//
019// This library is distributed in the hope that it will be useful,
020// but WITHOUT ANY WARRANTY; without even the implied warranty of
021// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
022// Lesser General Public License for more details.
023//
024// You should have received a copy of the GNU Lesser General Public
025// License along with this library; if not, write to the Free Software
026// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
027//
028// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
029// jataylor@hairyfatguy.com
030//------------------------------------------------------------------------------
031
032public class HexUtil
033{
034   private static final Pattern sHexPattern = Pattern.compile("#?[0-9A-F]+", Pattern.CASE_INSENSITIVE);
035
036   //---------------------------------------------------------------------------
037   /**
038    Returns whether or not the specified String could be a hexidecimal number.
039    */
040   public static boolean isHex(String inValue)
041   {
042      boolean result = false;
043      if (StringUtil.isSet(inValue))
044      {
045         result = sHexPattern.matcher(inValue).matches();
046      }
047
048      return result;
049   }
050
051   //---------------------------------------------------------------------------
052   public static byte[] hexStringToByteArray(String inHexString)
053   {
054      int len = inHexString.length();
055      byte[] data = new byte[len / 2];
056      for (int i = 0; i < len; i += 2)
057      {
058         data[i / 2] = (byte) ((Character.digit(inHexString.charAt(i), 16) << 4)
059                               + Character.digit(inHexString.charAt(i + 1), 16));
060      }
061
062      return data;
063   }
064
065   //---------------------------------------------------------------------------
066   public static String byteArrayToHexString(byte[] inValue)
067   {
068      StringBuilder result = new StringBuilder();
069      for (int i = 0; i < inValue.length; i++)
070      {
071         result.append(Integer.toString( ( inValue[i] & 0xff ) + 0x100, 16).substring( 1 ));
072      }
073
074      return result.toString();
075   }
076}