Java Tutorial/Data Type/Hex Oct

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

A custom number formatter that formats numbers as hexadecimal strings.

   <source lang="java">

/*

* JFreeChart : a free chart library for the Java(tm) platform
* 
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info:  http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* --------------------
* HexNumberFormat.java
* --------------------
* (C) Copyright 2007, 2008, by Richard West and Contributors.
*
* Original Author:  Richard West, Advanced Micro Devices, Inc.;
* Contributor(s):   David Gilbert (for Object Refinery Limited);
*
* Changes:
* --------
* 14-Jun-2007 : Version 1 (RW);
*
*/

import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; /**

* A custom number formatter that formats numbers as hexadecimal strings.
* There are some limitations, so be careful using this class.
*
* @since 1.0.6
*/

public class HexNumberFormat extends NumberFormat {

   /** Number of hexadecimal digits for a byte. */
   public static final int BYTE = 2;
   /** Number of hexadecimal digits for a word. */
   public static final int WORD = 4;
   /** Number of hexadecimal digits for a double word. */
   public static final int DWORD = 8;
   /** Number of hexadecimal digits for a quad word. */
   public static final int QWORD = 16;
   /** The number of digits (shorter strings will be left padded). */
   private int m_numDigits = DWORD;
   /**
    * Creates a new instance with 8 digits.
    */
   public HexNumberFormat() {
       this(DWORD);
   }
   /**
    * Creates a new instance with the specified number of digits.
    * @param digits  the digits.
    */
   public HexNumberFormat(int digits) {
       super();
       this.m_numDigits = digits;
   }
   /**
    * Returns the number of digits.
    *
    * @return The number of digits.
    */
   public final int getNumberOfDigits() {
       return this.m_numDigits;
   }
   /**
    * Sets the number of digits.
    *
    * @param digits  the number of digits.
    */
   public void setNumberOfDigits(int digits) {
       this.m_numDigits = digits;
   }
   /**
    * Formats the specified number as a hexadecimal string.  The decimal
    * fraction is ignored.
    *
    * @param number  the number to format.
    * @param toAppendTo  the buffer to append to (ignored here).
    * @param pos  the field position (ignored here).
    *
    * @return The string buffer.
    */
   public StringBuffer format(double number, StringBuffer toAppendTo,
           FieldPosition pos) {
       return format((long) number, toAppendTo, pos);
   }
   /**
    * Formats the specified number as a hexadecimal string.  The decimal
    * fraction is ignored.
    *
    * @param number  the number to format.
    * @param toAppendTo  the buffer to append to (ignored here).
    * @param pos  the field position (ignored here).
    *
    * @return The string buffer.
    */
   public StringBuffer format(long number, StringBuffer toAppendTo,
           FieldPosition pos) {
       String l_hex = Long.toHexString(number).toUpperCase();
       int l_pad = this.m_numDigits - l_hex.length();
       l_pad = (0 < l_pad) ? l_pad : 0;
       StringBuffer l_extended = new StringBuffer("0x");
       for (int i = 0; i < l_pad; i++) {
           l_extended.append(0);
       }
       l_extended.append(l_hex);
       return l_extended;
   }
   /**
    * Parsing is not implemented, so this method always returns
    * null.
    *
    * @param source  ignored.
    * @param parsePosition  ignored.
    *
    * @return Always null.
    */
   public Number parse (String source, ParsePosition parsePosition) {
       return null; // don"t bother with parsing
   }

}</source>





A hexadecimal literal of type long

Append L to the literal.



   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   long hexLongValue = 0x0FL;
   System.out.println(hexLongValue);
 }

}</source>



15


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 integer to hexadecimal number example

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   int i = 32;
   String strHexNumber = Integer.toHexString(i);
   System.out.println(strHexNumber);
 }

} //20</source>





Convert decimal integer to octal number example

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   int i = 27;
   String strOctalNumber = Integer.toOctalString(i);
   System.out.println(strOctalNumber);
 }

} //33</source>





Converting hexadecimal strings

   <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.
*/

/* $Id$ */

/**

* Provides helper functions for converting hexadecimal strings.
*/

public class HexUtil {

   private static final char[] DIGITS = 
       {"0", "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "A", "B", "C", "D", "E", "F"};
   /**
    * Converts a byte array to a hexadecimal String
    * @param data the data to encode
    * @return String the resulting String
    */
   public static final String toHex(byte[] data) {
       final StringBuffer sb = new StringBuffer(data.length * 2);
       for (int i = 0; i < data.length; i++) {
           sb.append(DIGITS[(data[i] >>> 4) & 0x0F]);
           sb.append(DIGITS[data[i] & 0x0F]);
       }
       return sb.toString();
   }
   

}</source>





Convert octal number to decimal number example

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   String strOctalNumber = "33";
   int decimalNumber = Integer.parseInt(strOctalNumber, 8);
   System.out.println(decimalNumber);
 }

} //27</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 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);
 }
 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>





Decodes Base64 data into octects

   <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.
*/

import java.io.UnsupportedEncodingException; /**

* This class provides encode/decode for RFC 2045 Base64 as
* defined by RFC 2045, N. Freed and N. Borenstein.
* RFC 2045: Multipurpose Internet Mail Extensions (MIME)
* Part One: Format of Internet Message Bodies. Reference
* 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
* This class is used by XML Schema binary format validation
*
* This implementation does not encode/decode streaming
* data. You need the data that you will encode/decode
* already on a byte arrray.
* 
* 
* From xmlbeans
* @author Jeffrey Rodriguez
* @author Sandy Gao
* @version $Id: Base64.java 111285 2004-12-08 16:54:26Z cezar $
*/

public final class Base64 {

   static private final int  BASELENGTH         = 255;
   static private final int  LOOKUPLENGTH       = 64;
   static private final int  TWENTYFOURBITGROUP = 24;
   static private final int  EIGHTBIT           = 8;
   static private final int  SIXTEENBIT         = 16;
   //static private final int  SIXBIT             = 6;
   static private final int  FOURBYTE           = 4;
   static private final int  SIGN               = -128;
   static private final byte PAD                = ( byte ) "=";
   static private final boolean fDebug          = false;
   static private byte [] base64Alphabet        = new byte[BASELENGTH];
   static private byte [] lookUpBase64Alphabet  = new byte[LOOKUPLENGTH];
   static {
       for (int i = 0; i<BASELENGTH; i++) {
           base64Alphabet[i] = -1;
       }
       for (int i = "Z"; i >= "A"; i--) {
           base64Alphabet[i] = (byte) (i-"A");
       }
       for (int i = "z"; i>= "a"; i--) {
           base64Alphabet[i] = (byte) ( i-"a" + 26);
       }
       for (int i = "9"; i >= "0"; i--) {
           base64Alphabet[i] = (byte) (i-"0" + 52);
       }
       base64Alphabet["+"]  = 62;
       base64Alphabet["/"]  = 63;
       for (int i = 0; i<=25; i++)
           lookUpBase64Alphabet[i] = (byte) ("A"+i );
       for (int i = 26,  j = 0; i<=51; i++, j++)
           lookUpBase64Alphabet[i] = (byte) ("a"+ j );
       for (int i = 52,  j = 0; i<=61; i++, j++)
           lookUpBase64Alphabet[i] = (byte) ("0" + j );
       lookUpBase64Alphabet[62] = (byte) "+";
       lookUpBase64Alphabet[63] = (byte) "/";
   }
   protected static boolean isWhiteSpace(byte octect) {
       return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
   }
   protected static boolean isPad(byte octect) {
       return (octect == PAD);
   }
   protected static boolean isData(byte octect) {
       return (base64Alphabet[octect] != -1);
   }
   protected static boolean isBase64(byte octect) {
       return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
   }
   /**
    * Encodes hex octects into Base64
    *
    * @param binaryData Array containing binaryData
    * @return Encoded Base64 array
    */
   public static byte[] encode(byte[] binaryData) {
       if (binaryData == null)
           return null;
       int      lengthDataBits    = binaryData.length*EIGHTBIT;
       int      fewerThan24bits   = lengthDataBits%TWENTYFOURBITGROUP;
       int      numberTriplets    = lengthDataBits/TWENTYFOURBITGROUP;
       byte     encodedData[]     = null;
       if (fewerThan24bits != 0) //data not divisible by 24 bit
           encodedData = new byte[ (numberTriplets + 1 )*4  ];
       else // 16 or 8 bit
           encodedData = new byte[ numberTriplets*4 ];
       byte k=0, l=0, b1=0,b2=0,b3=0;
       int encodedIndex = 0;
       int dataIndex   = 0;
       int i           = 0;
       if (fDebug) {
           System.out.println("number of triplets = " + numberTriplets );
       }
       for (i = 0; i<numberTriplets; i++) {
           dataIndex = i*3;
           b1 = binaryData[dataIndex];
           b2 = binaryData[dataIndex + 1];
           b3 = binaryData[dataIndex + 2];
           if (fDebug) {
               System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 );
           }
           l  = (byte)(b2 & 0x0f);
           k  = (byte)(b1 & 0x03);
           encodedIndex = i*4;
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
           byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
           encodedData[encodedIndex]   = lookUpBase64Alphabet[ val1 ];
           if (fDebug) {
               System.out.println( "val2 = " + val2 );
               System.out.println( "k4   = " + (k<<4));
               System.out.println( "vak  = " + (val2 | (k<<4)));
           }
           encodedData[encodedIndex+1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
           encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
           encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ];
       }
       // form integral number of 6-bit groups
       dataIndex    = i*3;
       encodedIndex = i*4;
       if (fewerThan24bits == EIGHTBIT) {
           b1 = binaryData[dataIndex];
           k = (byte) ( b1 &0x03 );
           if (fDebug) {
               System.out.println("b1=" + b1);
               System.out.println("b1<<2 = " + (b1>>2) );
           }
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           encodedData[encodedIndex]     = lookUpBase64Alphabet[ val1 ];
           encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ];
           encodedData[encodedIndex + 2] = PAD;
           encodedData[encodedIndex + 3] = PAD;
       } else if (fewerThan24bits == SIXTEENBIT) {
           b1 = binaryData[dataIndex];
           b2 = binaryData[dataIndex +1 ];
           l = ( byte ) ( b2 &0x0f );
           k = ( byte ) ( b1 &0x03 );
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
           encodedData[encodedIndex]     = lookUpBase64Alphabet[ val1 ];
           encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
           encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ];
           encodedData[encodedIndex + 3] = PAD;
       }
       return encodedData;
   }
   /**
    * Decodes Base64 data into octects
    *
    * @param base64Data Byte array containing Base64 data
    * @return Array containind decoded data.
    */
   public static byte[] decode(byte[] base64Data) {
       if (base64Data == null)
           return null;
       // remove white spaces
       base64Data = removeWhiteSpace(base64Data);
       if (base64Data.length%FOURBYTE != 0) {
           return null;//should be divisible by four
       }
       int      numberQuadruple    = (base64Data.length/FOURBYTE );
       if (numberQuadruple == 0)
           return new byte[0];
       byte     decodedData[]      = null;
       byte     b1=0,b2=0,b3=0, b4=0;//, marker0=0, marker1=0;
       byte     d1=0,d2=0,d3=0,d4=0;
       // Throw away anything not in normalizedBase64Data
       // Adjust size
       int i = 0;
       int encodedIndex = 0;
       int dataIndex    = 0;
       decodedData      = new byte[ (numberQuadruple)*3];
       for (; i<numberQuadruple-1; i++) {
           if (!isData( (d1 = base64Data[dataIndex++]) )||
               !isData( (d2 = base64Data[dataIndex++]) )||
               !isData( (d3 = base64Data[dataIndex++]) )||
               !isData( (d4 = base64Data[dataIndex++]) ))
               return null;//if found "no data" just return null
           b1 = base64Alphabet[d1];
           b2 = base64Alphabet[d2];
           b3 = base64Alphabet[d3];
           b4 = base64Alphabet[d4];
           decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
           decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
           decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
       }
       if (!isData( (d1 = base64Data[dataIndex++]) ) ||
           !isData( (d2 = base64Data[dataIndex++]) )) {
           return null;//if found "no data" just return null
       }
       b1 = base64Alphabet[d1];
       b2 = base64Alphabet[d2];
       d3 = base64Data[dataIndex++];
       d4 = base64Data[dataIndex++];
       if (!isData( (d3 ) ) ||
           !isData( (d4 ) )) {//Check if they are PAD characters
           if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
               if ((b2 & 0xf) != 0)//last 4 bits should be zero
                   return null;
               byte[] tmp = new byte[ i*3 + 1 ];
               System.arraycopy( decodedData, 0, tmp, 0, i*3 );
               tmp[encodedIndex]   = (byte)(  b1 <<2 | b2>>4 ) ;
               return tmp;
           } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
               b3 = base64Alphabet[ d3 ];
               if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
                   return null;
               byte[] tmp = new byte[ i*3 + 2 ];
               System.arraycopy( decodedData, 0, tmp, 0, i*3 );
               tmp[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 );
               tmp[encodedIndex]   = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
               return tmp;
           } else {
               return null;//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
           }
       } else { //No PAD e.g 3cQl
           b3 = base64Alphabet[ d3 ];
           b4 = base64Alphabet[ d4 ];
           decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
           decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
           decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
       }
       return decodedData;
   }

// /** // * Decodes Base64 data into octects // * // * @param base64Data String containing Base64 data // * @return string containing decoded data. // */ // public static String decode(String base64Data) { // if (base64Data == null) // return null; // // byte[] decoded = null; // try { // decoded = decode(base64Data.getBytes("utf-8")); // } // catch(UnsupportedEncodingException e) { // } // finally { // return decoded == null ? null : new String(decoded); // } // } // // /** // * Encodes octects (using utf-8) into Base64 data // * // * @param binaryData String containing Hex data // * @return string containing decoded data. // */ // public static String encode(String binaryData) { // if (binaryData == null) // return null; // // byte[] encoded = null; // try { // encoded = encode(binaryData.getBytes("utf-8")); // } // catch(UnsupportedEncodingException e) {} // finally { // return encoded == null ? null : new String(encoded); // } // }

   /**
    * remove WhiteSpace from MIME containing encoded Base64 data.
    *
    * @param data  the byte array of base64 data (with WS)
    * @return      the byte array of base64 data (without WS)
    */
   protected static byte[] removeWhiteSpace(byte[] data) {
       if (data == null)
           return null;
       // count characters that"s not whitespace
       int newSize = 0;
       int len = data.length;
       for (int i = 0; i < len; i++) {
           if (!isWhiteSpace(data[i]))
               newSize++;
       }
       // if no whitespace, just return the input array
       if (newSize == len)
           return data;
       // create the array to return
       byte[] newArray = new byte[newSize];
       int j = 0;
       for (int i = 0; i < len; i++) {
           if (!isWhiteSpace(data[i]))
               newArray[j++] = data[i];
       }
       return newArray;
   }

}</source>





Decodes Hex data into octects

   <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);
 }
 /**
  * Decodes Hex data into octects
  *
  * @param binaryData String containing Hex data
  * @return string containing decoded data.
  */
 public static String decode(String binaryData) {
     if (binaryData == null)
         return null;
     byte[] decoded = null;
     try {
       decoded = decode(binaryData.getBytes("utf-8"));
     }
     catch(UnsupportedEncodingException e) {
     }
     return decoded == null ? null : new String(decoded);
 }
 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>





Decode string to integer

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   String decimal = "10"; // Decimal
   String hexa = "0XFF"; // Hexa
   String octal = "077"; // Octal
   Integer number = Integer.decode(decimal);
   System.out.println("String [" + decimal + "] = " + number);
   number = Integer.decode(hexa);
   System.out.println("String [" + hexa + "] = " + number);
   number = Integer.decode(octal);
   System.out.println("String [" + octal + "] = " + number);
 }

}</source>





Defining integer literals as octal values

  1. Octal values is base 8
  2. Legal digits in an octal literal can be from 0 to 7
  3. Octal literals are with a leading zero, for example 035 and 067



   <source lang="java">

public class MainClass{

 public static void main(String[] a){
    int octValue = 036;
    System.out.println(octValue);
 }

}</source>



30


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>





Dumps data in hexadecimal format

   <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.IOException; import java.io.OutputStream; /**

* Dumps data in hexadecimal format.
* 
* Provides a single function to take an array of bytes and display it
* in hexadecimal form.
* 
* Origin of code: POI.
*
* @author Scott Sanders
* @author Marc Johnson
* @version $Id: HexDump.java 596667 2007-11-20 13:50:14Z niallp $
*/

public class HexDump {

   /**
    * Instances should NOT be constructed in standard programming.
    */
   public HexDump() {
       super();
   }
   /**
    * Dump an array of bytes to an OutputStream.
    *
    * @param data  the byte array to be dumped
    * @param offset  its offset, whatever that might mean
    * @param stream  the OutputStream to which the data is to be
    *               written
    * @param index initial index into the byte array
    *
    * @throws IOException is thrown if anything goes wrong writing
    *         the data to stream
    * @throws ArrayIndexOutOfBoundsException if the index is
    *         outside the data array"s bounds
    * @throws IllegalArgumentException if the output stream is null
    */
   public static void dump(byte[] data, long offset,
                           OutputStream stream, int index)
           throws IOException, ArrayIndexOutOfBoundsException,
           IllegalArgumentException {
       
       if ((index < 0) || (index >= data.length)) {
           throw new ArrayIndexOutOfBoundsException(
                   "illegal index: " + index + " into array of length "
                   + data.length);
       }
       if (stream == null) {
           throw new IllegalArgumentException("cannot write to nullstream");
       }
       long display_offset = offset + index;
       StringBuffer buffer = new StringBuffer(74);
       for (int j = index; j < data.length; j += 16) {
           int chars_read = data.length - j;
           if (chars_read > 16) {
               chars_read = 16;
           }
           dump(buffer, display_offset).append(" ");
           for (int k = 0; k < 16; k++) {
               if (k < chars_read) {
                   dump(buffer, data[k + j]);
               } else {
                   buffer.append("  ");
               }
               buffer.append(" ");
           }
           for (int k = 0; k < chars_read; k++) {
               if ((data[k + j] >= " ") && (data[k + j] < 127)) {
                   buffer.append((char) data[k + j]);
               } else {
                   buffer.append(".");
               }
           }
           buffer.append(EOL);
           stream.write(buffer.toString().getBytes());
           stream.flush();
           buffer.setLength(0);
           display_offset += chars_read;
       }
   }
   /**
    * The line-separator (initializes to "line.separator" system property.
    */
   public static final String EOL =
           System.getProperty("line.separator");
   private static final char[] _hexcodes =
           {
               "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
               "A", "B", "C", "D", "E", "F"
           };
   private static final int[] _shifts =
           {
               28, 24, 20, 16, 12, 8, 4, 0
           };
   /**
    * Dump a long value into a StringBuffer.
    *
    * @param _lbuffer the StringBuffer to dump the value in
    * @param value  the long value to be dumped
    * @return StringBuffer containing the dumped value.
    */
   private static StringBuffer dump(StringBuffer _lbuffer, long value) {
       for (int j = 0; j < 8; j++) {
           _lbuffer
                   .append(_hexcodes[((int) (value >> _shifts[j])) & 15]);
       }
       return _lbuffer;
   }
   /**
    * Dump a byte value into a StringBuffer.
    *
    * @param _cbuffer the StringBuffer to dump the value in
    * @param value  the byte value to be dumped
    * @return StringBuffer containing the dumped value.
    */
   private static StringBuffer dump(StringBuffer _cbuffer, byte value) {
       for (int j = 0; j < 2; j++) {
           _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]);
       }
       return _cbuffer;
   }

}</source>





Encodes hex octects into Base64

   <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.
*/

import java.io.UnsupportedEncodingException; /**

* This class provides encode/decode for RFC 2045 Base64 as
* defined by RFC 2045, N. Freed and N. Borenstein.
* RFC 2045: Multipurpose Internet Mail Extensions (MIME)
* Part One: Format of Internet Message Bodies. Reference
* 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
* This class is used by XML Schema binary format validation
*
* This implementation does not encode/decode streaming
* data. You need the data that you will encode/decode
* already on a byte arrray.
* 
* 
* From xmlbeans
* @author Jeffrey Rodriguez
* @author Sandy Gao
* @version $Id: Base64.java 111285 2004-12-08 16:54:26Z cezar $
*/

public final class Base64 {

   static private final int  BASELENGTH         = 255;
   static private final int  LOOKUPLENGTH       = 64;
   static private final int  TWENTYFOURBITGROUP = 24;
   static private final int  EIGHTBIT           = 8;
   static private final int  SIXTEENBIT         = 16;
   //static private final int  SIXBIT             = 6;
   static private final int  FOURBYTE           = 4;
   static private final int  SIGN               = -128;
   static private final byte PAD                = ( byte ) "=";
   static private final boolean fDebug          = false;
   static private byte [] base64Alphabet        = new byte[BASELENGTH];
   static private byte [] lookUpBase64Alphabet  = new byte[LOOKUPLENGTH];
   static {
       for (int i = 0; i<BASELENGTH; i++) {
           base64Alphabet[i] = -1;
       }
       for (int i = "Z"; i >= "A"; i--) {
           base64Alphabet[i] = (byte) (i-"A");
       }
       for (int i = "z"; i>= "a"; i--) {
           base64Alphabet[i] = (byte) ( i-"a" + 26);
       }
       for (int i = "9"; i >= "0"; i--) {
           base64Alphabet[i] = (byte) (i-"0" + 52);
       }
       base64Alphabet["+"]  = 62;
       base64Alphabet["/"]  = 63;
       for (int i = 0; i<=25; i++)
           lookUpBase64Alphabet[i] = (byte) ("A"+i );
       for (int i = 26,  j = 0; i<=51; i++, j++)
           lookUpBase64Alphabet[i] = (byte) ("a"+ j );
       for (int i = 52,  j = 0; i<=61; i++, j++)
           lookUpBase64Alphabet[i] = (byte) ("0" + j );
       lookUpBase64Alphabet[62] = (byte) "+";
       lookUpBase64Alphabet[63] = (byte) "/";
   }
   protected static boolean isWhiteSpace(byte octect) {
       return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
   }
   protected static boolean isPad(byte octect) {
       return (octect == PAD);
   }
   protected static boolean isData(byte octect) {
       return (base64Alphabet[octect] != -1);
   }
   protected static boolean isBase64(byte octect) {
       return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
   }
   /**
    * Encodes hex octects into Base64
    *
    * @param binaryData Array containing binaryData
    * @return Encoded Base64 array
    */
   public static byte[] encode(byte[] binaryData) {
       if (binaryData == null)
           return null;
       int      lengthDataBits    = binaryData.length*EIGHTBIT;
       int      fewerThan24bits   = lengthDataBits%TWENTYFOURBITGROUP;
       int      numberTriplets    = lengthDataBits/TWENTYFOURBITGROUP;
       byte     encodedData[]     = null;
       if (fewerThan24bits != 0) //data not divisible by 24 bit
           encodedData = new byte[ (numberTriplets + 1 )*4  ];
       else // 16 or 8 bit
           encodedData = new byte[ numberTriplets*4 ];
       byte k=0, l=0, b1=0,b2=0,b3=0;
       int encodedIndex = 0;
       int dataIndex   = 0;
       int i           = 0;
       if (fDebug) {
           System.out.println("number of triplets = " + numberTriplets );
       }
       for (i = 0; i<numberTriplets; i++) {
           dataIndex = i*3;
           b1 = binaryData[dataIndex];
           b2 = binaryData[dataIndex + 1];
           b3 = binaryData[dataIndex + 2];
           if (fDebug) {
               System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 );
           }
           l  = (byte)(b2 & 0x0f);
           k  = (byte)(b1 & 0x03);
           encodedIndex = i*4;
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
           byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
           encodedData[encodedIndex]   = lookUpBase64Alphabet[ val1 ];
           if (fDebug) {
               System.out.println( "val2 = " + val2 );
               System.out.println( "k4   = " + (k<<4));
               System.out.println( "vak  = " + (val2 | (k<<4)));
           }
           encodedData[encodedIndex+1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
           encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
           encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ];
       }
       // form integral number of 6-bit groups
       dataIndex    = i*3;
       encodedIndex = i*4;
       if (fewerThan24bits == EIGHTBIT) {
           b1 = binaryData[dataIndex];
           k = (byte) ( b1 &0x03 );
           if (fDebug) {
               System.out.println("b1=" + b1);
               System.out.println("b1<<2 = " + (b1>>2) );
           }
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           encodedData[encodedIndex]     = lookUpBase64Alphabet[ val1 ];
           encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ];
           encodedData[encodedIndex + 2] = PAD;
           encodedData[encodedIndex + 3] = PAD;
       } else if (fewerThan24bits == SIXTEENBIT) {
           b1 = binaryData[dataIndex];
           b2 = binaryData[dataIndex +1 ];
           l = ( byte ) ( b2 &0x0f );
           k = ( byte ) ( b1 &0x03 );
           byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
           byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
           encodedData[encodedIndex]     = lookUpBase64Alphabet[ val1 ];
           encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
           encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ];
           encodedData[encodedIndex + 3] = PAD;
       }
       return encodedData;
   }
   /**
    * Decodes Base64 data into octects
    *
    * @param base64Data Byte array containing Base64 data
    * @return Array containind decoded data.
    */
   public static byte[] decode(byte[] base64Data) {
       if (base64Data == null)
           return null;
       // remove white spaces
       base64Data = removeWhiteSpace(base64Data);
       if (base64Data.length%FOURBYTE != 0) {
           return null;//should be divisible by four
       }
       int      numberQuadruple    = (base64Data.length/FOURBYTE );
       if (numberQuadruple == 0)
           return new byte[0];
       byte     decodedData[]      = null;
       byte     b1=0,b2=0,b3=0, b4=0;//, marker0=0, marker1=0;
       byte     d1=0,d2=0,d3=0,d4=0;
       // Throw away anything not in normalizedBase64Data
       // Adjust size
       int i = 0;
       int encodedIndex = 0;
       int dataIndex    = 0;
       decodedData      = new byte[ (numberQuadruple)*3];
       for (; i<numberQuadruple-1; i++) {
           if (!isData( (d1 = base64Data[dataIndex++]) )||
               !isData( (d2 = base64Data[dataIndex++]) )||
               !isData( (d3 = base64Data[dataIndex++]) )||
               !isData( (d4 = base64Data[dataIndex++]) ))
               return null;//if found "no data" just return null
           b1 = base64Alphabet[d1];
           b2 = base64Alphabet[d2];
           b3 = base64Alphabet[d3];
           b4 = base64Alphabet[d4];
           decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
           decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
           decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
       }
       if (!isData( (d1 = base64Data[dataIndex++]) ) ||
           !isData( (d2 = base64Data[dataIndex++]) )) {
           return null;//if found "no data" just return null
       }
       b1 = base64Alphabet[d1];
       b2 = base64Alphabet[d2];
       d3 = base64Data[dataIndex++];
       d4 = base64Data[dataIndex++];
       if (!isData( (d3 ) ) ||
           !isData( (d4 ) )) {//Check if they are PAD characters
           if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
               if ((b2 & 0xf) != 0)//last 4 bits should be zero
                   return null;
               byte[] tmp = new byte[ i*3 + 1 ];
               System.arraycopy( decodedData, 0, tmp, 0, i*3 );
               tmp[encodedIndex]   = (byte)(  b1 <<2 | b2>>4 ) ;
               return tmp;
           } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
               b3 = base64Alphabet[ d3 ];
               if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
                   return null;
               byte[] tmp = new byte[ i*3 + 2 ];
               System.arraycopy( decodedData, 0, tmp, 0, i*3 );
               tmp[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 );
               tmp[encodedIndex]   = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
               return tmp;
           } else {
               return null;//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
           }
       } else { //No PAD e.g 3cQl
           b3 = base64Alphabet[ d3 ];
           b4 = base64Alphabet[ d4 ];
           decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
           decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
           decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
       }
       return decodedData;
   }

// /** // * Decodes Base64 data into octects // * // * @param base64Data String containing Base64 data // * @return string containing decoded data. // */ // public static String decode(String base64Data) { // if (base64Data == null) // return null; // // byte[] decoded = null; // try { // decoded = decode(base64Data.getBytes("utf-8")); // } // catch(UnsupportedEncodingException e) { // } // finally { // return decoded == null ? null : new String(decoded); // } // } // // /** // * Encodes octects (using utf-8) into Base64 data // * // * @param binaryData String containing Hex data // * @return string containing decoded data. // */ // public static String encode(String binaryData) { // if (binaryData == null) // return null; // // byte[] encoded = null; // try { // encoded = encode(binaryData.getBytes("utf-8")); // } // catch(UnsupportedEncodingException e) {} // finally { // return encoded == null ? null : new String(encoded); // } // }

   /**
    * remove WhiteSpace from MIME containing encoded Base64 data.
    *
    * @param data  the byte array of base64 data (with WS)
    * @return      the byte array of base64 data (without WS)
    */
   protected static byte[] removeWhiteSpace(byte[] data) {
       if (data == null)
           return null;
       // count characters that"s not whitespace
       int newSize = 0;
       int len = data.length;
       for (int i = 0; i < len; i++) {
           if (!isWhiteSpace(data[i]))
               newSize++;
       }
       // if no whitespace, just return the input array
       if (newSize == len)
           return data;
       // create the array to return
       byte[] newArray = new byte[newSize];
       int j = 0;
       for (int i = 0; i < len; i++) {
           if (!isWhiteSpace(data[i]))
               newArray[j++] = data[i];
       }
       return newArray;
   }

}</source>





Given a hexstring this will return the byte array corresponding to 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.
*/

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 a hexstring this will return the byte array corresponding to the
  * string
  * @param hex the hex String array
  * @return a byte array that is a hex string representation of the given
  *         string. The size of the byte array is therefore hex.length/2
  */
 public static byte[] hexStringToByte(String hex) {
   byte[] bts = new byte[hex.length() / 2];
   for (int i = 0; i < bts.length; i++) {
     bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
   }
   return bts;
 }

}</source>





Helper function that dump an array of bytes in hex pair form, without "0x" and space chars

   <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 pair form, 
  * without "0x" and space chars
  * 
  * @param buffer The bytes array to dump
  * @return A string representation of the array of bytes
  */
 public static final String dumpHexPairs( byte[] buffer )
 {
     if ( buffer == null )
     {
         return "";
     }
     StringBuffer sb = new StringBuffer();
     for ( int i = 0; i < buffer.length; i++ )
     {
         sb.append( ( char ) ( HEX_CHAR[( buffer[i] & 0x00F0 ) >> 4] ) ).append(
             ( char ) ( HEX_CHAR[buffer[i] & 0x000F] ) );
     }
     return sb.toString();
 }

}</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>





Hexadecimal integer literal

  1. Put 0x or 0X in front of the numbers.
  2. Use the letters A to F (or a to f) to represent digits with values 10 to 15, respectively.



   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   int hexValue1 = 0x100;
   int hexValue2 = 0x1234;
   int hexValue3 = 0xDEAF;
   int hexValue4 = 0xCAB;
   System.out.println(hexValue1);
   System.out.println(hexValue2);
   System.out.println(hexValue3);
   System.out.println(hexValue4);
 }

}</source>



256
4660
57007
3243


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>





Parsing and Formatting a Number into Binary

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   int i = 1023;

   i = Integer.parseInt("1111111111", 2);
   String s = Integer.toString(i, 2); 
   System.out.println(s);
 }

}</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>