Java/Data Type/Hexadecimal

Материал из Java эксперт
Перейти к: навигация, поиск

append hex digit

   <source lang="java">
    

// // Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /**

* Fast String Utilities.
* 
* These string utilities provide both conveniance methods and performance
* improvements over most standard library versions. The main aim of the
* optimizations is to avoid object creation unless absolutely required.
* 
* @author Greg Wilkins (gregw)
*/

public class Utils {

 /**
  * append hex digit
  * 
  */
 public static void append(StringBuffer buf, byte b, int base) {
   int bi = 0xff & b;
   int c = "0" + (bi / base) % base;
   if (c > "9")
     c = "a" + (c - "0" - 10);
   buf.append((char) c);
   c = "0" + bi % base;
   if (c > "9")
     c = "a" + (c - "0" - 10);
   buf.append((char) c);
 }
 /* ------------------------------------------------------------ */
 public static void append2digits(StringBuffer buf, int i) {
   if (i < 100) {
     buf.append((char) (i / 10 + "0"));
     buf.append((char) (i % 10 + "0"));
   }
 }

}



 </source>
   
  
 
  



Check if the current character is an Hex Char <hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66]

   <source lang="java">
  

import java.io.File; import java.io.FileFilter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*

*  Licensed to the Apache Software Foundation (ASF) under one
*  or more contributor license agreements.  See the NOTICE file
*  distributed with this work for additional information
*  regarding copyright ownership.  The ASF licenses this file
*  to you under the Apache License, Version 2.0 (the
*  "License"); you may not use this file except in compliance
*  with the License.  You may obtain a copy of the License at
*  
*    http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing,
*  software distributed under the License is distributed on an
*  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*  KIND, either express or implied.  See the License for the
*  specific language governing permissions and limitations
*  under the License. 
*  
*/

/**

* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
* 
* @author 
*/

public class Main {

 /** <hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */
 private static final boolean[] HEX =
     { 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         true,  true,  true,  true,  true,  true,  true,  true, 
         true,  true,  false, false, false, false, false, false, 
         false, true,  true,  true,  true,  true,  true,  false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, true,  true,  true,  true,  true,  true,  false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false, 
         false, false, false, false, false, false, false, false };
 /**
  * Check if the current character is an Hex Char <hex> ::= [0x30-0x39] |
  * [0x41-0x46] | [0x61-0x66]
  * 
  * @param byteArray
  *            The buffer which contains the data
  * @param index
  *            Current position in the buffer
  * @return true if the current character is a Hex Char
  */
 public static final boolean isHex( byte[] byteArray, int index )
 {
     if ( ( byteArray == null ) || ( byteArray.length == 0 ) || ( index < 0 ) || ( index >= byteArray.length ) )
     {
         return false;
     }
     else
     {
         byte c = byteArray[index];
         if ( ( ( c | 0x7F ) != 0x7F ) || ( HEX[c] == false ) )
         {
             return false;
         }
         else
         {
             return true;
         }
     }
 }

}


 </source>
   
  
 
  



Convert byte array to Hex String

   <source lang="java">
     

/*

   JSPWiki - a JSP-based WikiWiki clone.
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.    
*/

import java.security.SecureRandom; import java.util.Random; public class StringUtils {

 /**
  *  Generates a hexadecimal string from an array of bytes.  For
  *  example, if the array contains { 0x01, 0x02, 0x3E }, the resulting
  *  string will be "01023E".
  *
  * @param bytes A Byte array
  * @return A String representation
  * @since 2.3.87
  */
 public static String toHexString( byte[] bytes )
 {
     StringBuffer sb = new StringBuffer( bytes.length*2 );
     for( int i = 0; i < bytes.length; i++ )
     {
         sb.append( toHex(bytes[i] >> 4) );
         sb.append( toHex(bytes[i]) );
     }
     return sb.toString();
 }
 private static char toHex(int nibble)
 {
     final char[] hexDigit =
     {
         "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
     };
     return hexDigit[nibble & 0xF];
 }

}




 </source>
   
  
 
  



Convert Decimal to Hexadecimal

   <source lang="java">
       

public class Main {

 public static void main(String[] args) {
   System.out.println(Integer.toHexString(1976));
   System.out.println(Integer.parseInt("7b8", 16));
 }

}





 </source>
   
  
 
  



Convert from Byte array to hexadecimal string

   <source lang="java">
       

public class Main {

 public static void main(String[] args) throws Exception {
   int i = Integer.valueOf("1234A", 16).intValue();
   // or
   i = Integer.parseInt("BBA", 16);
 }

}





 </source>
   
  
 
  



Convert from decimal to hexadecimal

   <source lang="java">
       

public class Main {

 public static void main(String[] args) throws Exception {
   int i = 42;
   String hexstr = Integer.toString(i, 16);
   System.out.println(hexstr);
   hexstr = Integer.toHexString(i);
   System.out.println(hexstr);
   
 }

} /* 2a 2a

  • /





 </source>
   
  
 
  



Convert from decimal to hexadecimal with leading zeroes and uppercase

   <source lang="java">
       

public class Main {

 public static void main(String[] args) throws Exception {
    System.out.print(Integer.toHexString(0x10000 | i).substring(1).toUpperCase());
 }

}





 </source>
   
  
 
  



Converts a hex string to a byte array.

   <source lang="java">
     

/* Copyright 2004 The Apache Software Foundation

*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*  limitations under the License.
*/

//xmlbeans import java.io.UnsupportedEncodingException; /**

* format validation
*
* This class encodes/decodes hexadecimal data
* @author Jeffrey Rodriguez
* @version $Id: HexBin.java 125124 2005-01-14 00:23:54Z kkrouse $
*/

public class Main {

 static private final int  BASELENGTH   = 255;
 static private final int  LOOKUPLENGTH = 16;
 static private byte [] hexNumberTable    = new byte[BASELENGTH];
 static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH];
 static {
     for (int i = 0; i<BASELENGTH; i++ ) {
         hexNumberTable[i] = -1;
     }
     for ( int i = "9"; i >= "0"; i--) {
         hexNumberTable[i] = (byte) (i-"0");
     }
     for ( int i = "F"; i>= "A"; i--) {
         hexNumberTable[i] = (byte) ( i-"A" + 10 );
     }
     for ( int i = "f"; i>= "a"; i--) {
        hexNumberTable[i] = (byte) ( i-"a" + 10 );
     }
     for(int i = 0; i<10; i++ )
         lookUpHexAlphabet[i] = (byte) ("0"+i );
     for(int i = 10; i<=15; i++ )
         lookUpHexAlphabet[i] = (byte) ("A"+i -10);
 }
 /**
  * Converts a hex string to a byte array.
  */
 static public byte[] stringToBytes(String hexEncoded)
 {
     return decode(hexEncoded.getBytes());
 }
 static public byte[] decode(byte[] binaryData) {
     if (binaryData == null)
         return null;
     int lengthData   = binaryData.length;
     if (lengthData % 2 != 0)
         return null;
     int lengthDecode = lengthData / 2;
     byte[] decodedData = new byte[lengthDecode];
     for( int i = 0; i<lengthDecode; i++ ){
         if (!isHex(binaryData[i*2]) || !isHex(binaryData[i*2+1])) {
             return null;
         }
         decodedData[i] = (byte)((hexNumberTable[binaryData[i*2]] << 4) | hexNumberTable[binaryData[i*2+1]]);
     }
     return decodedData;
 }
 /**
  * byte to be tested if it is Base64 alphabet
  *
  * @param octect
  * @return
  */
 static boolean isHex(byte octect) {
     return (hexNumberTable[octect] != -1);
 }

}




 </source>
   
  
 
  



Convert the bytes to a hex string representation of the bytes

   <source lang="java">
     

/**

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.Collection;

/**

* General string utils
*/

public class StringUtils {

 final public static char COMMA = ",";
 final public static String COMMA_STR = ",";
 final public static char ESCAPE_CHAR = "\\";
 private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
 
 /**
  * Given an array of bytes it will convert the bytes to a hex string
  * representation of the bytes
  * @param bytes
  * @return hex string representation of the byte array
  */
 public static String byteToHexString(byte bytes[]) {
   StringBuffer retString = new StringBuffer();
   for (int i = 0; i < bytes.length; ++i) {
     retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF))
                      .substring(1));
   }
   return retString.toString();
 }

}




 </source>
   
  
 
  



Decode hex string to a byte array

   <source lang="java">
      

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* format validation
*
* This class encodes/decodes hexadecimal data
* 
* @xerces.internal  
* 
* @author Jeffrey Rodriguez
* @version $Id: HexBin.java 446747 2006-09-15 21:46:20Z mrglavas $
*/

public final class HexBin {

   static private final int  BASELENGTH   = 128;
   static private final int  LOOKUPLENGTH = 16;
   static final private byte [] hexNumberTable    = new byte[BASELENGTH];
   static final private char [] lookUpHexAlphabet = new char[LOOKUPLENGTH];
   static {
       for (int i = 0; i < BASELENGTH; i++ ) {
           hexNumberTable[i] = -1;
       }
       for ( int i = "9"; i >= "0"; i--) {
           hexNumberTable[i] = (byte) (i-"0");
       }
       for ( int i = "F"; i>= "A"; i--) {
           hexNumberTable[i] = (byte) ( i-"A" + 10 );
       }
       for ( int i = "f"; i>= "a"; i--) {
          hexNumberTable[i] = (byte) ( i-"a" + 10 );
       }
       for(int i = 0; i<10; i++ ) {
           lookUpHexAlphabet[i] = (char)("0"+i);
       }
       for(int i = 10; i<=15; i++ ) {
           lookUpHexAlphabet[i] = (char)("A"+i -10);
       }
   }
   /**
    * Decode hex string to a byte array
    *
    * @param encoded encoded string
    * @return return array of byte to encode
    */
   static public byte[] decode(String encoded) {
       if (encoded == null)
           return null;
       int lengthData = encoded.length();
       if (lengthData % 2 != 0)
           return null;
       char[] binaryData = encoded.toCharArray();
       int lengthDecode = lengthData / 2;
       byte[] decodedData = new byte[lengthDecode];
       byte temp1, temp2;
       char tempChar;
       for( int i = 0; i<lengthDecode; i++ ){
           tempChar = binaryData[i*2];
           temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
           if (temp1 == -1)
               return null;
           tempChar = binaryData[i*2+1];
           temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
           if (temp2 == -1)
               return null;
           decodedData[i] = (byte)((temp1 << 4) | temp2);
       }
       return decodedData;
   }

}




 </source>
   
  
 
  



dump an array of bytes in hex form

   <source lang="java">
  

import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*

*  Licensed to the Apache Software Foundation (ASF) under one
*  or more contributor license agreements.  See the NOTICE file
*  distributed with this work for additional information
*  regarding copyright ownership.  The ASF licenses this file
*  to you under the Apache License, Version 2.0 (the
*  "License"); you may not use this file except in compliance
*  with the License.  You may obtain a copy of the License at
*  
*    http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing,
*  software distributed under the License is distributed on an
*  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*  KIND, either express or implied.  See the License for the
*  specific language governing permissions and limitations
*  under the License. 
*  
*/

/**

* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
* 
* @author 
*/

public class Main {

 /** Hex chars */
 private static final byte[] HEX_CHAR = new byte[]
     { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
 /**
  * Helper function that dump an array of bytes in hex form
  * 
  * @param buffer
  *            The bytes array to dump
  * @return A string representation of the array of bytes
  */
 public static final String dumpBytes( byte[] buffer )
 {
     if ( buffer == null )
     {
         return "";
     }
     StringBuffer sb = new StringBuffer();
     for ( int i = 0; i < buffer.length; i++ )
     {
         sb.append( "0x" ).append( ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ) ).append(
             ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ) ).append( " " );
     }
     return sb.toString();
 }

}


 </source>
   
  
 
  



Get Base64 From HEX

   <source lang="java">
      

/*

* $Header: /cvsroot/mvnforum/mvnforum/contrib/phpbb2mvnforum/src/org/mvnforum/util/MD5.java,v 1.6 2007/01/15 10:27:31 dungbtm Exp $
* $Author: dungbtm $
* $Revision: 1.6 $
* $Date: 2007/01/15 10:27:31 $
*
* 
*
* Copyright (C) 2002-2007 by MyVietnam.net
*
* All copyright notices regarding mvnForum MUST remain 
* intact in the scripts and in the outputted HTML.
* The "powered by" text/logo with a link back to
* http://www.mvnForum.ru and http://www.MyVietnam.net in 
* the footer of the pages MUST remain visible when the pages
* are viewed on the internet or intranet.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
* Support can be obtained from support forums at:
* http://www.mvnForum.ru/mvnforum/index
*
* Correspondence and Marketing Questions can be sent to:
* info at MyVietnam net
*
* @author: 
*/

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; // // The JavaReference.ru Software License, Version 1.0 // Copyright (c) 2002-2005 JavaReference.ru. All rights reserved. // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. The end-user documentation included with the redistribution, if any, must // include the following acknowlegement: // // "This product includes software developed by the Javareference.ru // (http://www.javareference.ru/)." // // Alternately, this acknowlegement may appear in the software itself, if and // wherever such third-party acknowlegements normally appear. // // 4. The names "JavaReference" and "Javareference.ru", must not be used to // endorse or promote products derived from this software without prior written // permission. For written permission, please contact webmaster@javareference.ru. // // 5. Products derived from this software may not be called "Javareference" nor may // "Javareference" appear in their names without prior written permission of // Javareference.ru. // // THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // JAVAREFERENCE.ru OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // // Software from this site consists of contributions made by various individuals // on behalf of Javareference.ru. For more information on Javareference.ru, // please see http://www.javareference.ru // /**

* @author anandh
*/

public class MD5 {

   static char[] carr = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
   public static String getBase64FromHEX(String input) {
       
       byte barr[] = new byte[16];
       int bcnt = 0;
       for (int i = 0; i < 32; i += 2) {
           char c1 = input.charAt(i);
           char c2 = input.charAt(i + 1);
           int i1 = intFromChar(c1);
           int i2 = intFromChar(c2);
           barr[bcnt] = 0;
           barr[bcnt] |= (byte) ((i1 & 0x0F) << 4);
           barr[bcnt] |= (byte) (i2 & 0x0F);
           bcnt++;
       }
       BASE64Encoder encoder = new BASE64Encoder();
       return encoder.encode(barr);
   }
   public static synchronized String getMD5_Base64(String input) {
       // please note that we dont use digest, because if we
       // cannot get digest, then the second time we have to call it
       // again, which will fail again
       MessageDigest digest = null;
       try {
           digest = MessageDigest.getInstance("MD5");
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       if (digest == null)
           return input;
       // now everything is ok, go ahead
       try {
           digest.update(input.getBytes("UTF-8"));
       } catch (java.io.UnsupportedEncodingException ex) {
           ex.printStackTrace();
       }
       byte[] rawData = digest.digest();
       BASE64Encoder bencoder = new BASE64Encoder();
       return bencoder.encode(rawData);
   }
   private static int intFromChar(char c) {
       char clower = Character.toLowerCase(c);
       for (int i = 0; i < carr.length; i++) {
           if (clower == carr[i]) {
               return i;
           }
       }
       return 0;
   }
   public static void main(String[] args) {
       
       //String password = args[0];
       String password = "test";
       MessageDigest digest = null;
       try {
           digest = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
       }
       try {
           digest.update(password.getBytes("UTF-8"));
       } catch (UnsupportedEncodingException ex) {
           ex.printStackTrace();
       }
       byte[] rawData = digest.digest();
       StringBuffer printable = new StringBuffer();
       for (int i = 0; i < rawData.length; i++) {
           printable.append(carr[((rawData[i] & 0xF0) >> 4)]);
           printable.append(carr[(rawData[i] & 0x0F)]);
       }
       String phpbbPassword = printable.toString();
       System.out.println("PHPBB           : " + phpbbPassword);
       System.out.println("MVNFORUM        : " + getMD5_Base64(password));
       System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword));
   }

}




 </source>
   
  
 
  



Get byte array from hex string

   <source lang="java">
  

/*

*  Licensed to the Apache Software Foundation (ASF) under one
*  or more contributor license agreements.  See the NOTICE file
*  distributed with this work for additional information
*  regarding copyright ownership.  The ASF licenses this file
*  to you under the Apache License, Version 2.0 (the
*  "License"); you may not use this file except in compliance
*  with the License.  You may obtain a copy of the License at
*  
*    http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing,
*  software distributed under the License is distributed on an
*  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*  KIND, either express or implied.  See the License for the
*  specific language governing permissions and limitations
*  under the License. 
*  
*/

/**

* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
* 
* @author 
*/

public class Main {

 /** lowerCase = "a" .. "z", "0".."9", "-" */
 private static final char[] LOWER_CASE =
     { 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0, "-",   0,   0, 
         "0", "1", "2", "3", "4", "5", "6", "7", 
         "8", "9",   0,   0,   0,   0,   0,   0, 
           0, "a", "b", "c", "d", "e", "f", "g", 
         "h", "i", "j", "k", "l", "m", "n", "o", 
         "p", "q", "r", "s", "t", "u", "v", "w", 
         "x", "y", "z",   0,   0,   0,   0,   0, 
           0, "a", "b", "c", "d", "e", "f", "g", 
         "h", "i", "j", "k", "l", "m", "n", "o", 
         "p", "q", "r", "s", "t", "u", "v", "w", 
         "x", "y", "z",   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0, 
           0,   0,   0,   0,   0,   0,   0,   0 
     };
 /**
  * Get byte array from hex string
  * 
  * @param hexString
  *            the hex string to convert to a byte array
  * @return the byte form of the hex string.
  */
 public static final byte[] toByteArray( String hexString )
 {
     int arrLength = hexString.length() >> 1;
     byte buf[] = new byte[arrLength];
     
     for ( int ii = 0; ii < arrLength; ii++ )
     {
         int index = ii << 1;
         
         String l_digit = hexString.substring( index, index + 2 );
         buf[ii] = ( byte ) Integer.parseInt( l_digit, 16 );
     }
     
     return buf;
 }

}


 </source>
   
  
 
  



Helper function that returns a char from an hex

   <source lang="java">
  

import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*

*  Licensed to the Apache Software Foundation (ASF) under one
*  or more contributor license agreements.  See the NOTICE file
*  distributed with this work for additional information
*  regarding copyright ownership.  The ASF licenses this file
*  to you under the Apache License, Version 2.0 (the
*  "License"); you may not use this file except in compliance
*  with the License.  You may obtain a copy of the License at
*  
*    http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing,
*  software distributed under the License is distributed on an
*  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*  KIND, either express or implied.  See the License for the
*  specific language governing permissions and limitations
*  under the License. 
*  
*/

/**

* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
* 
* @author 
*/

public class Main {

 /** Hex chars */
 private static final byte[] HEX_CHAR = new byte[]
     { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
 /**
  * Helper function that returns a char from an hex
  * 
  * @param hex The hex to dump
  * @return A char representation of the hex
  */
 public static final char dumpHex( byte hex )
 {
     return ( char ) HEX_CHAR[hex & 0x000F];
 }

}


 </source>
   
  
 
  



Hex decimal dump

   <source lang="java">
      

import java.math.BigDecimal; /*

*  Dump.java
*
*  Projeto ECFbabel
*
*  Copyright 2005-2007 Daniel "Spanazzi" Gonçalves
*  
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*  
*      http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**

*  Fornece métodos para produç�o de dumps hexadecimais a partir de arrays de bytes ou 
*  de inteiros (inteiros representando bytes sem sinal, entre 0 e 255). Um dump 
*  hexadecimal produzido pelo método dump(byte[]) é parecido com o
*  seguinte exemplo:
*
*
 *    Titulo do dump aqui
 *    000000  38 19 4A 14 F9 12 91 52-73 89 BA F9 F3 2E 00 CC  8.J....Rs.......
 *    000010  FB 37 7A 88 35 87 30 47-39 C1 DD D6 C9 F5 1F 11  .7z.5.0G9.......
 *    000020  E6 A6 C1 7D 4E 27 C1 A6-55 17 99 34 19 17 30 C9  ...}N"..U..4..0.
 *    000030  CC 68 C4 2B 74 2B 83 9D-59 15 3B 86 B9 F1 9D 07  .h.+t+..Y.;.....
 *    000040  9F 14 99 AE C6 A2 C6 40-EC 27 2C 55 61 F7 2A 63  .......@.",Ua.*c
 *    000050  8C AD 82 22 68 11 CE 24-41 9C 8B 93 DA AA 62 3C  ..."h..$A.....b<
 *    000060  C5 17 BD 49 6F 19 E4 F7-9D 3B 4C 33 14 15 81 66  ...Io....;L3...f
 *    000070  97 BA A4 29 70 B2 81 04-35 08 AA 6D 8D 6E 6F 54  ...)p...5..m.noT
 *    000080  9C DA 6A 28 F6 B4 C2 D7-BD 01 D0 6C D7 CC 8D 04  ..j(.......l....
 *    000090  29 BA 0F 87 21 B2 99 52-7B E5 19 5C 4D F7 6A 32  )...!..R{..\M.j2
 *    0000A0  36 A4 77 58 33 67 54 EF-C0 62 3F 19 29 D6 A7 A2  6.wX3gT..b?.)...
 *    0000B0  77 54 B0 3E DE 3E 83 1B-FE 22 4E EF 8C F7 99 88  wT.>.>..."N.....
 *    0000C0  55 6B CE 9E 75 A3 50 B7-FA A5 59 2A 41 34 7D 56  Uk..u.P...Y*A4}V
 *    0000D0  FA E6 FD 0A 77 36 C5 52-C4 E3                    ....w6.R..
 *    Dump: 218 byte(s)
 *  
*
*

Também fornece diversos métodos convenientes para log de dumps hexadecimais.

*
*  @since Outubro/2007
*
*  @version $Id: Dump.java,v 1.1.1.1 2008/03/12 03:29:34 rawfosgod Exp $
*
*  @author Daniel Gonçalves
*/

public final class Dump {


     /**
      *  Constrói um buffer string contendo um dumping hexadecimal do array de
      *  inteiros.
      *
      *  @param data array de inteiros. Cada elemento do array deverá ser um valor
      *         que represente um byte sem sinal, entre 0 e 255, inclusive.
      */
     public static String dump(final int[] data) {
           return dump(ByteUtils.itob(data));
     }
     
     /**
      *  Constrói um buffer string contendo um dumping hexadecimal do array de
      *  bytes especificado.
      *
      *  @param data array de dados.
      *
      *  @return buffer string contendo o dump hexadecimal.
      */
     public static String dump(final byte[] data) {
           String eol = System.getProperty("line.separator");
           StringBuilder buffer = new StringBuilder();
           int offset = 0;
           int column = 0;
           StringBuilder hexDump = new StringBuilder();
           StringBuilder chrDump = new StringBuilder();
           for (int pos = 0; pos < data.length; pos++) {
                 hexDump.append(hex((int)(data[pos] & 0xff), 2));
                 chrDump.append(chr((int)(data[pos] & 0xff)));
                 column++;
                 if (column > 15) {
                       buffer.append("  ")
                             .append(hex(offset, 6)) .append("  ")
                             .append(hexDump)        .append("  ")
                             .append(chrDump)        .append(eol);
                       column = 0;
                       offset += 16;
                       hexDump = new StringBuilder();
                       chrDump = new StringBuilder();
                 }
                 else {
                       if (column == 8) {
                             // inclui um separador "-" entre a 8a. e 9a. colunas
                             hexDump.append("-");
                       }
                       else {
                             // separa com 1 espaço os valores hexadecimais dos bytes
                             hexDump.append(" ");
                       }
                 }
                 
           }
           
           if ((column != 0) && (column < 15)) {
                 // completa a linha com espaços até a 16a. posiç�o
                 while (column < 16) {
                       hexDump.append("   "); // 3 espaços
                       chrDump.append(" "); // 1 espaço
                       column++;
                 }
                 // remove o último espaço da sequência
                 hexDump.deleteCharAt(hexDump.length()-1); 
                 buffer.append("  ")
                       .append(hex(offset, 6)) .append("  ")
                       .append(hexDump)        .append("  ")
                       .append(chrDump)        .append(eol);
           }
           
           // inclui o rodapé, indicando o total de bytes no dump
           buffer.append("  Dump: ").append(data.length).append(" byte(s).").append(eol);
           
           return buffer.toString(); 
     } // dump(byte[])
     
     /**
      *  Retorna uma string de tamanho fixo, contendo a representaç�o hexadecimal do valor.
      *
      *  @param value valor inteiro, de base 10, a ser convertido para base 16.
      *
      *  @param length comprimento total desejado. 
      *
      *  @return Representaç�o hexadecimal do valor com o comprimento especificado.
      *          A string resultante será completada com zeros à esquerda até que o
      *          comprimento total desejado seja atingido.
      *          Se a representaç�o hexadecimal do valor resultar em um comprimento maior 
      *          que o especificado, a string resultante será formada de asteriscos,
      *          indicando que o comprimento especificado n�o foi suficiente para o valor. 
      */
     public static String hex(final int value, final int length) {
           StringBuilder str = new StringBuilder(Integer.toString(value, 16).toUpperCase());
           if (str.length() < length) {
                 int falta = (length - str.length());
                 for (int i = 1; i <= falta; i++) {
                       str.insert(0, "0");
                 }
           }
           else if (str.length() > length) {
                 str = new StringBuilder();
                 for (int i = 1; i <= length; i++) {
                       str.append("*");
                 }
           }
           return str.toString();
     }
     private static String chr(final int value) {
           if ((value < 32) || (value > 127)) {
                 return ".";
           }
           return new String(new byte[] { (byte)(value & 0xff) });
     }
     

} // {{{ Dump }}} /*

*  ByteUtils.java
*
*  Projeto ECFbabel
*
*  Copyright 2005-2007 Daniel "Spanazzi" Gonçalves
*  
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*  
*      http://www.apache.org/licenses/LICENSE-2.0
*  
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

/**

*  TODO: documentar!  
*
*  @since Setembro/2007
*
*  @version $Id: ByteUtils.java,v 1.1.1.1 2008/03/12 03:29:33 rawfosgod Exp $
*
*  @author Daniel Gonçalves
*/
final class ByteUtils {
     
     private ByteUtils() {}
     
     /**
      *  Retorna o byte de baixa ordem a partir de um valor inteiro.
      *
      *  @param value valor inteiro (até 65535).
      *
      *  @return byte de baixa ordem do valor. Por exemplo, o byte de
      *          baixa ordem para o valor 1234 é 210.
      */
     public static int lo(final int value) {
           int low = value;
           if (value > 255) low = Math.abs(value % 256);
           return low;
     }
     
     /**
      *  Retorna o byte de alta ordem a partir de um valor inteiro.
      * 
      *  @param value valor inteiro (até 65535).
      *
      *  @return byte de alta ordem do valor. Por exemplo, o byte de 
      *          alta ordem para o valor 1234 é 4.
      */
     public static int hi(final int value) {
           int high = 0;
           if (value > 255) high = Math.abs((int)(value / 256));
           return high;
     }
     
     /**
      *  Converte 2 bytes sem sinal no formato Intel Low/High para um inteiro.
      *  Como no exemplo:
      *
*
       *      int valor = 1234; // "100 1101 0010"
       *      int hi = ByteUtils.hi(valor);  // resulta: 4  "100"
       *      int lo = ByteUtils.lo(valor);  // resulta: 210  "1101 0010"
       *      int test = ByteUtils.hilo2int(hi, lo) // resulta: 1234  "100 1101 0010"
       *  
      *
      *  @param high byte de alta ordem (deve ser um valor entre 0 e 255 inclusive).
      *  @param low byte de baixa ordem (deve ser um valor entre 0 e 255 inclusive).
      *
      *  @return valor inteiro até 65535 representados pelos bytes de alta e baixa ordem. 
      */
     public static int hilo2int(int high, int low) {
           return (low | (high << 8));
     }
     
     public static byte[] itob(int[] ints) {
           byte[] bytes = new byte[ints.length];
           for (int i = 0; i < ints.length; i++) bytes[i] = (byte)(ints[i] & 0xff);
           return bytes;
     }
     
     public static int[] btoi(byte[] bytes) {
           int[] ints = new int[bytes.length];
           for (int i = 0; i < bytes.length; i++) ints[i] = (int)(bytes[i] & 0xff);
           return ints;
     }
     
     /**
      *  Extrai o valor ASCII de um determinado caracter de uma string. Por exemplo:
      * 
*
       *  ByteUtils.ascval("ABC", 0); // resulta: 65
       *  ByteUtils.ascval("ABC", 1); // resulta: 66
       *  ByteUtils.ascval("ABC", 2); // resulta: 67
       *  
      *
      *  @param s a string alvo.
      *
      *  @param pos a posiç�o a ser extraído o valor ASCII.
      *
      *  @return o valor ASCII do caracter na posiç�o pos da string
      *          s.
      *
      *  @throws IndexOutOfBoundsException se a posiç�o indicada for menor que zero ou
      *          maior que o tamanho da string s.length() - 1.
      */
     public static int ascval(String s, int pos) {
           return (int)((((byte)(s.charAt(pos))) & 0xff));
     }
     /**
      *  Converte uma string contendo uma sequência decimal codificada em BCD
      *  (Binary-Coded Decimal ?). Esta implementaç�o foi obtida a partir da
      *  descriç�o da codificaç�o BCD encontrada no manual de programaç�o das 
      *  impressoras fiscais Bematech® MP-20 FI II.
      *
*

Se os valores ASCII dos caracteres de uma string forem 0x12, 0x34 e * 0x56, ent�o bcd(s, 2) resultará no valor decimal * 1234.56.

      *
      *  @param s a string contendo a sequência BCD.
      *
      *  @param scale o número de casas decimais a serem considerados. Se este
      *         argumento for menor ou igual a zero, será considerado um valor
      *         inteiro.
      *
      *  @return um objeto java.math.BigDecimal contendo o valor
      *          decimal decodificado.
      *
      *  @throws NumberFormatException se a string s n�o representar
      *          uma sequência BCD válida.
      */
     public static BigDecimal bcd(final String s, final int scale) {
           StringBuilder hexval = new StringBuilder();
           // converte os valores ASCII da string para hexadecimal
           for (int i = 0; i < s.length(); i++) {
                 StringBuilder hex = new StringBuilder(Integer.toString(ascval(s, i), 16));
                 if (hex.length() != 2) hex.insert(0, "0");
                 hexval.append(hex);
           }
           if (scale > 0) {
                 if (scale > hexval.length()) {
                       // completa com zeros antes da posiç�o de inserç�o do ponto decimal
                       int count = scale - hexval.length();
                       for (int i = 1; i <= count; i++) hexval.insert(0, "0");
                 }
                 // insere um ponto decimal na posiç�o indicada
                 hexval.insert(hexval.length()-scale, ".");
           }
           return new BigDecimal(hexval.toString());
     }
     

} // {{{ ByteUtils }}}




 </source>
   
  
 
  



hex decoder

   <source lang="java">
      

/*

* Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved.
*
* Modified by Tomas Gustavsson
*/

import java.io.*; import java.math.BigInteger; /**

* This class implements a hex decoder, decoding a string with hex-characters into
* the binary form.
*
* @version $Id: Hex.java,v 1.4 2004/04/15 07:28:36 hamgert Exp $
*
*/

public class Hex {

   static private final char hex[] = {
       "0", "1", "2", "3", "4", "5", "6", "7",
       "8", "9", "a", "b", "c", "d", "e", "f"
   };
   /**
    * Encodar binärt till hex
    *
    *@param dataStr bin-representation av data
    *@return Hex-representation av data
    **/
   public static String encode(byte[] dataStr) {
       StringWriter w = new StringWriter();
       for (int i = 0; i < dataStr.length; i++) {
           int b = dataStr[i];
           w.write(hex[((b >> 4) & 0xF)]);
           w.write(hex[((b >> 0) & 0xF)]);
       }
       return w.toString();
   }
   /**
    * Decodar hex till binärt
    *
    *@param dataStr Sträng innehållande hex-representation av data
    *@return byte[] innhållande binär representation av data
    **/
   public static byte[] decode(String dataStr) {
       if ((dataStr.length() & 0x01) == 0x01)
           dataStr = new String(dataStr + "0");
       BigInteger cI = new BigInteger(dataStr, 16);
       byte[] data = cI.toByteArray();
       return data;
   } //decode
   public static void main(String[] args) {
       if (args.length != 3) {
           System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>");
           System.exit(1);
       }
       try {
           ByteArrayOutputStream os = new ByteArrayOutputStream();
           InputStream in = new FileInputStream(args[1]);
           int len = 0;
           byte buf[] = new byte[1024];
           while ((len = in.read(buf)) > 0)
               os.write(buf, 0, len);
           in.close();
           os.close();
           byte[] data = null;
           if (args[0].equals("dec"))
               data = decode(os.toString());
           else {
               String strData = encode(os.toByteArray());
               data = strData.getBytes();
           }
           FileOutputStream fos = new FileOutputStream(args[2]);
           fos.write(data);
           fos.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   } //main

} // Hex




 </source>
   
  
 
  



Hex encoder and decoder.

   <source lang="java">
      

/*

* Copyright 2001-2004 The Apache Software Foundation.
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Hex encoder and decoder.
* 
* @since 1.1
* @author Apache Software Foundation
* @version $Id: Hex.java,v 1.13 2004/04/18 18:22:33 ggregory Exp $
*/

public class Hex {

 /**
  * Used building output as Hex
  */
 private static final char[] DIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
     "b", "c", "d", "e", "f" };
 /**
  * Converts an array of characters representing hexidecimal values into an
  * array of bytes of those same values. The returned array will be half the
  * length of the passed array, as it takes two characters to represent any
  * given byte. An exception is thrown if the passed char array has an odd
  * number of elements.
  * 
  * @param data
  *          An array of characters containing hexidecimal digits
  * @return A byte array containing binary data decoded from the supplied char
  *         array.
  * @throws DecoderException
  *           Thrown if an odd number or illegal of characters is supplied
  */
 public static byte[] decodeHex(char[] data) throws RuntimeException {
   int len = data.length;
   if ((len & 0x01) != 0) {
     throw new RuntimeException("Odd number of characters.");
   }
   byte[] out = new byte[len >> 1];
   // two characters form the hex value.
   for (int i = 0, j = 0; j < len; i++) {
     int f = toDigit(data[j], j) << 4;
     j++;
     f = f | toDigit(data[j], j);
     j++;
     out[i] = (byte) (f & 0xFF);
   }
   return out;
 }
 /**
  * Converts a hexadecimal character to an integer.
  * 
  * @param ch
  *          A character to convert to an integer digit
  * @param index
  *          The index of the character in the source
  * @return An integer
  * @throws DecoderException
  *           Thrown if ch is an illegal hex character
  */
 protected static int toDigit(char ch, int index) throws RuntimeException {
   int digit = Character.digit(ch, 16);
   if (digit == -1) {
     throw new RuntimeException("Illegal hexadecimal charcter " + ch + " at index " + index);
   }
   return digit;
 }
 /**
  * Converts an array of bytes into an array of characters representing the
  * hexidecimal values of each byte in order. The returned array will be double
  * the length of the passed array, as it takes two characters to represent any
  * given byte.
  * 
  * @param data
  *          a byte[] to convert to Hex characters
  * @return A char[] containing hexidecimal characters
  */
 public static char[] encodeHex(byte[] data) {
   int l = data.length;
   char[] out = new char[l << 1];
   // two characters form the hex value.
   for (int i = 0, j = 0; i < l; i++) {
     out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
     out[j++] = DIGITS[0x0F & data[i]];
   }
   return out;
 }
 /**
  * Converts an array of character bytes representing hexidecimal values into
  * an array of bytes of those same values. The returned array will be half the
  * length of the passed array, as it takes two characters to represent any
  * given byte. An exception is thrown if the passed char array has an odd
  * number of elements.
  * 
  * @param array
  *          An array of character bytes containing hexidecimal digits
  * @return A byte array containing binary data decoded from the supplied byte
  *         array (representing characters).
  * @throws DecoderException
  *           Thrown if an odd number of characters is supplied to this
  *           function
  * @see #decodeHex(char[])
  */
 public byte[] decode(byte[] array) throws RuntimeException {
   return decodeHex(new String(array).toCharArray());
 }
 /**
  * Converts a String or an array of character bytes representing hexidecimal
  * values into an array of bytes of those same values. The returned array will
  * be half the length of the passed String or array, as it takes two
  * characters to represent any given byte. An exception is thrown if the
  * passed char array has an odd number of elements.
  * 
  * @param object
  *          A String or, an array of character bytes containing hexidecimal
  *          digits
  * @return A byte array containing binary data decoded from the supplied byte
  *         array (representing characters).
  * @throws DecoderException
  *           Thrown if an odd number of characters is supplied to this
  *           function or the object is not a String or char[]
  * @see #decodeHex(char[])
  */
 public Object decode(Object object) throws RuntimeException {
   try {
     char[] charArray = object instanceof String ? ((String) object).toCharArray()
         : (char[]) object;
     return decodeHex(charArray);
   } catch (ClassCastException e) {
     throw new RuntimeException(e.getMessage());
   }
 }
 /**
  * Converts an array of bytes into an array of bytes for the characters
  * representing the hexidecimal values of each byte in order. The returned
  * array will be double the length of the passed array, as it takes two
  * characters to represent any given byte.
  * 
  * @param array
  *          a byte[] to convert to Hex characters
  * @return A byte[] containing the bytes of the hexidecimal characters
  * @see #encodeHex(byte[])
  */
 public byte[] encode(byte[] array) {
   return new String(encodeHex(array)).getBytes();
 }
 /**
  * Converts a String or an array of bytes into an array of characters
  * representing the hexidecimal values of each byte in order. The returned
  * array will be double the length of the passed String or array, as it takes
  * two characters to represent any given byte.
  * 
  * @param object
  *          a String, or byte[] to convert to Hex characters
  * @return A char[] containing hexidecimal characters
  * @throws EncoderException
  *           Thrown if the given object is not a String or byte[]
  * @see #encodeHex(byte[])
  */
 public Object encode(Object object) throws Exception {
   try {
     byte[] byteArray = object instanceof String ? ((String) object).getBytes() : (byte[]) object;
     return encodeHex(byteArray);
   } catch (ClassCastException e) {
     throw new RuntimeException(e.getMessage());
   }
 }

}




 </source>
   
  
 
  



Hex encoder/decoder implementation borrowed from BouncyCastle

   <source lang="java">

/*

* Copyright 2007 Werner Guttmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.IOException; import java.io.OutputStream; import java.io.ByteArrayOutputStream; /**

* Hex encoder/decoder implementation (borrowed from BouncyCastle=.
* 
* @author Johan Lindquist
* @since 1.1.1
* @version $Revision$
*/

public final class HexDecoder {

   /**
    * Identifies the data type supported by this decoder.
    */
   public static final String DATA_TYPE = "hexBinary";
   /**
    * Initial size of the decoding table.
    */
   private static final int DECODING_TABLE_SIZE = 128;
   /**
    * Encoding table.
    */
   protected static final byte[] ENCODING_TABLE = {
       (byte) "0", (byte) "1", (byte) "2", (byte) "3",
       (byte) "4", (byte) "5", (byte) "6", (byte) "7",
       (byte) "8", (byte) "9", (byte) "A", (byte) "B",
       (byte) "C", (byte) "D", (byte) "E", (byte) "F" 
   };
   /**
    * Decoding table.
    */
   protected static final byte[] DECODING_TABLE = new byte[DECODING_TABLE_SIZE];
   /**
    * Initialize the decoding table.
    */
   protected static void initialiseDecodingTable() {
       for (int i = 0; i < ENCODING_TABLE.length; i++) {
           DECODING_TABLE[ENCODING_TABLE[i]] = (byte) i;
       }
       // deal with lower case letters as well
       DECODING_TABLE["a"] = DECODING_TABLE["A"];
       DECODING_TABLE["b"] = DECODING_TABLE["B"];
       DECODING_TABLE["c"] = DECODING_TABLE["C"];
       DECODING_TABLE["d"] = DECODING_TABLE["D"];
       DECODING_TABLE["e"] = DECODING_TABLE["E"];
       DECODING_TABLE["f"] = DECODING_TABLE["F"];
   }
   static {
       initialiseDecodingTable();
   }
   /**
    * Creates an instance of this class. 
    */
   private HexDecoder() {
       // Nothing to do ...
   }
   /**
    * Encodes the input data producing a Hex output stream.
    * @param data The input data to be HEX encoded
    * @param off Initiak offset
    * @param length Initial length of the input data array
    * @param out The {@link OutputStream} instance holding the encoded input data.
    * @return the number of bytes produced.
    * @throws IOException If encoding fails.
    */
   public static int encode(final byte[] data, final int off, final int length, 
           final OutputStream out) throws IOException {
       for (int i = off; i < (off + length); i++) {
           int v = data[i] & 0xff;
           out.write(ENCODING_TABLE[(v >>> 4)]);
           out.write(ENCODING_TABLE[v & 0xf]);
       }
       return length * 2;
   }
   /**
    * Indicates whether a given character should be ignored during en-/decoding.
    * @param c The character at question.
    * @return True if the given character should be ignored.
    */
   private static boolean ignore(final char c) {
       return (c == "\n" || c == "\r" || c == "\t" || c == " ");
   }
   /**
    * Decodes the Hex encoded byte data writing it to the given output stream,
    * whitespace characters will be ignored.
    * @param data The data to be encoded
    * @param off Initial offset.
    * @param length Initial length
    * @param out The {@link OutputStream} instance
    * @return the number of bytes produced.
    * @throws IOException If encoding failed.
    */
   public static int decode(final byte[] data, final int off, final int length,
           final OutputStream out) throws IOException {
       byte b1, b2;
       int outLen = 0;
       int end = off + length;
       while (end > off) {
           if (!ignore((char) data[end - 1])) {
               break;
           }
           end--;
       }
       int i = off;
       while (i < end) {
           while (i < end && ignore((char) data[i])) {
               i++;
           }
           b1 = DECODING_TABLE[data[i++]];
           while (i < end && ignore((char) data[i])) {
               i++;
           }
           b2 = DECODING_TABLE[data[i++]];
           out.write((b1 << 4) | b2);
           outLen++;
       }
       return outLen;
   }
   /**
    * Decodes the Hex encoded String data writing it to the given output stream,
    * whitespace characters will be ignored.
    * 
    * @param data The data to be encoded
    * @param out The {@link OutputStream} instance
    * @return the number of bytes produced.
    * @throws IOException If encoding failed.
    */
   public static int decode(final String data, final OutputStream out) throws IOException {
       byte b1, b2;
       int length = 0;
       int end = data.length();
       while (end > 0) {
           if (!ignore(data.charAt(end - 1))) {
               break;
           }
           end--;
       }
       int i = 0;
       while (i < end) {
           while (i < end && ignore(data.charAt(i))) {
               i++;
           }
           b1 = DECODING_TABLE[data.charAt(i++)];
           while (i < end && ignore(data.charAt(i))) {
               i++;
           }
           b2 = DECODING_TABLE[data.charAt(i++)];
           out.write((b1 << 4) | b2);
           length++;
       }
       return length;
   }
   /**
    * Encodes the input data producing a Hex output stream.
    * @param data Input data to encode.
    * @return the number of bytes produced.
    */
   public static String encode(final byte[] data) {
       try {
           final ByteArrayOutputStream out = new ByteArrayOutputStream();
           encode(data, 0, data.length, out);
           out.close();
           return new String(out.toByteArray());
       } catch (IOException e) {
           e.printStackTrace();
           throw new RuntimeException(e.getMessage(), e);
       }
   }
   /**
    * Decodes the HEX input data producing a output stream.
    * @param data Input data to be decoded.
    * @return A byte array representing the decoded input data.
    */
   public static byte[] decode(final String data) {
       try {
           final ByteArrayOutputStream out = new ByteArrayOutputStream();
           decode(data, out);
           out.close();
           return out.toByteArray();
       } catch (IOException e) {
           e.printStackTrace();
           throw new RuntimeException(e.getMessage(), e);
       }
   }

}

 </source>
   
  
 
  



Returns the hexadecimal value of the supplied byte array

   <source lang="java">
      

/*

* Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
*
* Licensed under the Aduna BSD-style license.
*/

public class Utils {

 /**
  * Returns the hexadecimal value of the supplied byte array. The resulting
  * string always uses two hexadecimals per byte. As a result, the length
  * of the resulting string is guaranteed to be twice the length of the
  * supplied byte array.
  */
 public static String toHexString(byte[] array) {
   StringBuilder sb = new StringBuilder(2*array.length);
   for (int i = 0; i < array.length; i++) {
     String hex = Integer.toHexString(array[i] & 0xff);
     if (hex.length() == 1) {
       sb.append("0");
     }
     sb.append(hex);
   }
   return sb.toString();
 }

}




 </source>