Java Tutorial/File/Byte Array

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

An optimized reader for reading byte streams that only contain 7-bit ASCII characters.

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

* A simple ASCII byte reader. This is an optimized reader for reading
* byte streams that only contain 7-bit ASCII characters.
*
* @author Andy Clark, IBM
*
* @version $Id: ASCIIReader.java 793 2008-09-27 17:44:11Z remy.maucherat@jboss.ru $
*/

public class ASCIIReader

   extends Reader {
   //
   // Constants
   //
   /** Default byte buffer size (2048). */
   public static final int DEFAULT_BUFFER_SIZE = 2048;
   //
   // Data
   //
   /** Input stream. */
   protected InputStream fInputStream;
   /** Byte buffer. */
   protected byte[] fBuffer;
   //
   // Constructors
   //
   /** 
    * Constructs an ASCII reader from the specified input stream 
    * and buffer size.
    *
    * @param inputStream The input stream.
    * @param size        The initial buffer size.
    */
   public ASCIIReader(InputStream inputStream, int size) {
       fInputStream = inputStream;
       fBuffer = new byte[size];
   }
   //
   // Reader methods
   //
   /**
    * Read a single character.  This method will block until a character is
    * available, an I/O error occurs, or the end of the stream is reached.
    *
    *  Subclasses that intend to support efficient single-character input
    * should override this method.
    *
    * @return     The character read, as an integer in the range 0 to 127
    *             (0x00-0x7f), or -1 if the end of the stream has
    *             been reached
    *
    * @exception  IOException  If an I/O error occurs
    */
   public int read() throws IOException {
       int b0 = fInputStream.read();
       if (b0 > 0x80) {
           throw new IOException("invalidASCII");
       }
       return b0;
   } // read():int
   /**
    * Read characters into a portion of an array.  This method will block
    * until some input is available, an I/O error occurs, or the end of the
    * stream is reached.
    *
    * @param      ch     Destination buffer
    * @param      offset Offset at which to start storing characters
    * @param      length Maximum number of characters to read
    *
    * @return     The number of characters read, or -1 if the end of the
    *             stream has been reached
    *
    * @exception  IOException  If an I/O error occurs
    */
   public int read(char ch[], int offset, int length) throws IOException {
       if (length > fBuffer.length) {
           length = fBuffer.length;
       }
       int count = fInputStream.read(fBuffer, 0, length);
       for (int i = 0; i < count; i++) {
           int b0 = (0xff & fBuffer[i]); // Convert to unsigned
           if (b0 > 0x80) {
               throw new IOException("invalidASCII");
           }
           ch[offset + i] = (char)b0;
       }
       return count;
   } // read(char[],int,int)
   /**
    * Skip characters.  This method will block until some characters are
    * available, an I/O error occurs, or the end of the stream is reached.
    *
    * @param  n  The number of characters to skip
    *
    * @return    The number of characters actually skipped
    *
    * @exception  IOException  If an I/O error occurs
    */
   public long skip(long n) throws IOException {
       return fInputStream.skip(n);
   } // skip(long):long
   /**
    * Tell whether this stream is ready to be read.
    *
    * @return True if the next read() is guaranteed not to block for input,
    * false otherwise.  Note that returning false does not guarantee that the
    * next read will block.
    *
    * @exception  IOException  If an I/O error occurs
    */
   public boolean ready() throws IOException {
 return false;
   } // ready()
   /**
    * Tell whether this stream supports the mark() operation.
    */
   public boolean markSupported() {
 return fInputStream.markSupported();
   } // markSupported()
   /**
    * Mark the present position in the stream.  Subsequent calls to reset()
    * will attempt to reposition the stream to this point.  Not all
    * character-input streams support the mark() operation.
    *
    * @param  readAheadLimit  Limit on the number of characters that may be
    *                         read while still preserving the mark.  After
    *                         reading this many characters, attempting to
    *                         reset the stream may fail.
    *
    * @exception  IOException  If the stream does not support mark(),
    *                          or if some other I/O error occurs
    */
   public void mark(int readAheadLimit) throws IOException {
 fInputStream.mark(readAheadLimit);
   } // mark(int)
   /**
    * Reset the stream.  If the stream has been marked, then attempt to
    * reposition it at the mark.  If the stream has not been marked, then
    * attempt to reset it in some way appropriate to the particular stream,
    * for example by repositioning it to its starting point.  Not all
    * character-input streams support the reset() operation, and some support
    * reset() without supporting mark().
    *
    * @exception  IOException  If the stream has not been marked,
    *                          or if the mark has been invalidated,
    *                          or if the stream does not support reset(),
    *                          or if some other I/O error occurs
    */
   public void reset() throws IOException {
       fInputStream.reset();
   } // reset()
   /**
    * Close the stream.  Once a stream has been closed, further read(),
    * ready(), mark(), or reset() invocations will throw an IOException.
    * Closing a previously-closed stream, however, has no effect.
    *
    * @exception  IOException  If an I/O error occurs
    */
    public void close() throws IOException {
        fInputStream.close();
    } // close()

} // class ASCIIReader</source>





Convert a base16 string into 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.    
*/

/**

* Base 16 encoder.
*
* @author Marc Prud"hommeaux
* @nojavadoc
*/
class Base16Encoder {
   private final static char[] HEX = new char[]{
       "0", "1", "2", "3", "4", "5", "6", "7",
       "8", "9", "A", "B", "C", "D", "E", "F" };
   /**
    * Convert bytes to a base16 string.
    */
   public static String encode(byte[] byteArray) {
       StringBuffer hexBuffer = new StringBuffer(byteArray.length * 2);
       for (int i = 0; i < byteArray.length; i++)
           for (int j = 1; j >= 0; j--)
               hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]);
       return hexBuffer.toString();
   }
   /**
    * Convert a base16 string into a byte array.
    */
   public static byte[] decode(String s) {
       int len = s.length();
       byte[] r = new byte[len / 2];
       for (int i = 0; i < r.length; i++) {
           int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1);
           if (digit1 >= "0" && digit1 <= "9")
               digit1 -= "0";
           else if (digit1 >= "A" && digit1 <= "F")
               digit1 -= "A" - 10;
           if (digit2 >= "0" && digit2 <= "9")
               digit2 -= "0";
           else if (digit2 >= "A" && digit2 <= "F")
               digit2 -= "A" - 10;
           r[i] = (byte) ((digit1 << 4) + digit2);
       }
       return r;
   }

}</source>





Convert a byte array to a human-readable String for debugging purposes.

   <source lang="java">

import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Locale; import java.util.Properties; /*

  Derby - Class org.apache.derby.iapi.util.PropertyUtil
  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.
*/

public class Main {

 private static char[] hex_table = {
   "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
   "a", "b", "c", "d", "e", "f"

};

 /**
   Convert a byte array to a human-readable String for debugging purposes.
 */
 public static String hexDump(byte[] data)
 {
           byte byte_value;
           StringBuffer str = new StringBuffer(data.length * 3);
           str.append("Hex dump:\n");
           for (int i = 0; i < data.length; i += 16)
           {
               // dump the header: 00000000: 
               String offset = Integer.toHexString(i);
               // "0" left pad offset field so it is always 8 char"s long.
               for (int offlen = offset.length(); offlen < 8; offlen++) 
                   str.append("0");
               str.append(offset);
               str.append(":");
               // dump hex version of 16 bytes per line.
               for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
               {
                   byte_value = data[i + j];
                   // add spaces between every 2 bytes.
                   if ((j % 2) == 0)
                       str.append(" ");
                   // dump a single byte.
                   byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4); 
                   byte low_nibble  = (byte) (byte_value & 0x0f); 
                   str.append(hex_table[high_nibble]);
                   str.append(hex_table[low_nibble]);
               }
               // dump ascii version of 16 bytes
               str.append("  ");
               for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
               {
                   char char_value = (char) data[i + j]; 
                   // RESOLVE (really want isAscii() or isPrintable())
                   if (Character.isLetterOrDigit(char_value))
                       str.append(String.valueOf(char_value));
                   else
                       str.append(".");
               }
                   
               // new line
               str.append("\n");
           }
           return(str.toString());
 }

}</source>





Convert Byte array to Int

   <source lang="java">

/*

* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA  02110-1301  USA
*
*/

public final class BytesHelper {

 private BytesHelper() {}
 public static int toInt( byte[] bytes ) {
   int result = 0;
   for (int i=0; i<4; i++) {
     result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
   }
   return result;
 }
 

}</source>





Convert byte array to string

   <source lang="java">

/*

  Copyright (C) 2002 MySQL AB
    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
    (at your option) 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
    
*/

import java.io.UnsupportedEncodingException;

/**

* Various utility methods for converting to/from byte
* arrays in the platform encoding
* 
* @author Mark Matthews
*/

public class StringUtils {

   //~ Instance/static variables .............................................
   private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE)
                                         - Byte.MIN_VALUE;
   private static byte[] allBytes = new byte[BYTE_RANGE];
   private static char[] byteToChars = new char[BYTE_RANGE];
   //~ Initializers ..........................................................
   static {
       for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
           allBytes[i - Byte.MIN_VALUE] = (byte) i;
       }
       String allBytesString = new String(allBytes, 0, 
                                          Byte.MAX_VALUE - Byte.MIN_VALUE);
       for (int i = 0; i < (Byte.MAX_VALUE - Byte.MIN_VALUE); i++) {
           byteToChars[i] = allBytesString.charAt(i);
       }
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString3(byte[] buffer, int startPos, 
                                             int length) {
       char[] charArray = new char[length];
       int readpoint = startPos;
       for (int i = 0; i < length; i++) {
           charArray[i] = byteToChars[(int) buffer[readpoint]
                          - Byte.MIN_VALUE];
           readpoint++;
       }
       return new String(charArray);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString(byte[] buffer) {
       return toAsciiString3(buffer, 0, buffer.length);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString2(byte[] buffer, int startPos, 
                                             int length) {
       return new String(buffer, startPos, length);
   }
   /**
    * DOCUMENT ME!
    * 
    * @param buffer DOCUMENT ME!
    * @param startPos DOCUMENT ME!
    * @param length DOCUMENT ME!
    * @return DOCUMENT ME! 
    */
   public static final String toAsciiString(byte[] buffer, int startPos, 
                                            int length) {
       StringBuffer result = new StringBuffer();
       int endPoint = startPos + length;
       for (int i = startPos; i < endPoint; i++) {
           result.append(byteToChars[(int) buffer[i] - Byte.MIN_VALUE]);
       }
       return result.toString();
   }

}</source>





Converts a byte array into a hexadecimal string

   <source lang="java">

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.

* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the Hypersonic SQL Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 THE HYPERSONIC SQL GROUP,
* OR 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.
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Hypersonic SQL Group.
*
*
* For work added by the HSQL Development Group:
*
* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR 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.
*/

/**

* Collection of static methods for converting strings between different formats
* and to and from byte arrays.
* 
* 
* Includes some methods based on Hypersonic code as indicated.
* 
* @author Thomas Mueller (Hypersonic SQL Group)
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/

public class Main {

 private static final byte[] HEXBYTES = { (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" };
 /**
  * Converts a byte array into a hexadecimal string
  * 
  * 
  * @param b
  *          byte array
  * 
  * @return hex string
  */
 public static String byteArrayToHexString(byte[] b) {
   int len = b.length;
   char[] s = new char[len * 2];
   for (int i = 0, j = 0; i < len; i++) {
     int c = ((int) b[i]) & 0xff;
     s[j++] = (char) HEXBYTES[c >> 4 & 0xf];
     s[j++] = (char) HEXBYTES[c & 0xf];
   }
   return new String(s);
 }

}</source>





Converts a byte array into hexadecimal characters which are written as ASCII to the given output stream.

   <source lang="java">

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.

* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the Hypersonic SQL Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 THE HYPERSONIC SQL GROUP,
* OR 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.
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Hypersonic SQL Group.
*
*
* For work added by the HSQL Development Group:
*
* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR 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.
*/

/**

* Collection of static methods for converting strings between different formats
* and to and from byte arrays.
* 
* 
* Includes some methods based on Hypersonic code as indicated.
* 
* @author Thomas Mueller (Hypersonic SQL Group)
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/

public class Main {

 private static final byte[] HEXBYTES = { (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" };
 /**
  * Converts a byte array into hexadecimal characters which are written as
  * ASCII to the given output stream.
  *
  * @param o output array
  * @param from offset into output array
  * @param b input array
  */
 public static void writeHexBytes(byte[] o, int from, byte[] b) {
     int len = b.length;
     for (int i = 0; i < len; i++) {
         int c = ((int) b[i]) & 0xff;
         o[from++] = HEXBYTES[c >> 4 & 0xf];
         o[from++] = HEXBYTES[c & 0xf];
     }
 }

}</source>





Convert the bytes within the specified range of the given byte array into a signed integer in the given radix

   <source lang="java">

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed integer in the given radix . The range extends from
  * start till, but not including end.
  * 
  * 
  * Based on java.lang.Integer.parseInt()
  */
 public static int parseInt(byte[] b, int start, int end, int radix) throws NumberFormatException {
   if (b == null)
     throw new NumberFormatException("null");
   int result = 0;
   boolean negative = false;
   int i = start;
   int limit;
   int multmin;
   int digit;
   if (end > start) {
     if (b[i] == "-") {
       negative = true;
       limit = Integer.MIN_VALUE;
       i++;
     } else {
       limit = -Integer.MAX_VALUE;
     }
     multmin = limit / radix;
     if (i < end) {
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number: " + toString(b, start, end));
       } else {
         result = -digit;
       }
     }
     while (i < end) {
       // Accumulating negatively avoids surprises near MAX_VALUE
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number");
       }
       if (result < multmin) {
         throw new NumberFormatException("illegal number");
       }
       result *= radix;
       if (result < limit + digit) {
         throw new NumberFormatException("illegal number");
       }
       result -= digit;
     }
   } else {
     throw new NumberFormatException("illegal number");
   }
   if (negative) {
     if (i > start + 1) {
       return result;
     } else { /* Only got "-" */
       throw new NumberFormatException("illegal number");
     }
   } else {
     return -result;
   }
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * 
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

}</source>





Convert the bytes within the specified range of the given byte array into a String

   <source lang="java">

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * 
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

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





Encode a byte array to 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.
*/

/**

* 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);
       }
   }
   /**
    * Encode a byte array to hex string
    *
    * @param binaryData array of byte to encode
    * @return return encoded string
    */
   static public String encode(byte[] binaryData) {
       if (binaryData == null)
           return null;
       int lengthData   = binaryData.length;
       int lengthEncode = lengthData * 2;
       char[] encodedData = new char[lengthEncode];
       int temp;
       for (int i = 0; i < lengthData; i++) {
           temp = binaryData[i];
           if (temp < 0)
               temp += 256;
           encodedData[i*2] = lookUpHexAlphabet[temp >> 4];
           encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf];
       }
       return new String(encodedData);
   }

}</source>





Get bytes from InputStream

   <source lang="java">

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 public static byte[] getBytes(InputStream is) throws IOException {
   int len;
   int size = 1024;
   byte[] buf;
   if (is instanceof ByteArrayInputStream) {
     size = is.available();
     buf = new byte[size];
     len = is.read(buf, 0, size);
   } else {
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     buf = new byte[size];
     while ((len = is.read(buf, 0, size)) != -1)
       bos.write(buf, 0, len);
     buf = bos.toByteArray();
   }
   return buf;
 }

}</source>





Gets an array of bytes corresponding to the given object

   <source lang="java">

/**

* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: Serialization.java 1970 2007-10-16 11:49:25Z benoitf $
* --------------------------------------------------------------------------
*/

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; /**

* Allow to get the bytes of an object or to recreate an object from bytes.
* It also used a custom reader when recreating object as it uses the context * classloader in order to have an object with the right classloader. * @author Florent Benoit */

public final class Serialization {

   /**
    * Gets an array of bytes corresponding to the given object.
    * @param object the object to serialize
    * @return an array of bytes.
    * @throws IOException if the object can"t be turned into an array of bytes.
    */
   public static byte[] storeObject(final Serializable object) throws IOException {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       ObjectOutputStream oos  =  null;
       try {
           oos = new ObjectOutputStream(baos);
           oos.writeObject(object);
           oos.flush();
           return baos.toByteArray();
       } finally {
           if (oos != null)  {
               oos.close();
           }
           if (baos != null) {
               baos.close();
           }
       }
   }

}</source>





Load File as byte array

   <source lang="java">

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   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 St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

/*

* Created on Mar 19, 2005
*/

import java.io.*; /**

* @author J. H. S.
*/

public class IORoutines {

 public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; 
 
 public static String loadAsText(InputStream in, String encoding) throws IOException {
   return loadAsText(in, encoding, 4096);
 }
 
 public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException {
   InputStreamReader reader = new InputStreamReader(in, encoding);
     char[] buffer = new char[bufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         char[] newBuffer = new char[buffer.length * 2];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = reader.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     return new String(buffer, 0, offset);
 }
 
   public static byte[] load(File file) throws IOException {
       long fileLength = file.length();
       if(fileLength > Integer.MAX_VALUE) {
           throw new IOException("File "" + file.getName() + "" too big");
       }
       InputStream in = new FileInputStream(file);
       try {
         return loadExact(in, (int) fileLength);
       } finally {
           in.close();
       }
   }
   
   public static byte[] load(InputStream in) throws IOException {
       return load(in, 4096);
   }
   public static byte[] load(InputStream in, int initialBufferSize) throws IOException {
     if(initialBufferSize == 0) {
       initialBufferSize = 1;
     }
     byte[] buffer = new byte[initialBufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         int newSize = buffer.length * 2;
         byte[] newBuffer = new byte[newSize];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = in.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     if(offset < buffer.length) {
       byte[] newBuffer = new byte[offset];
       System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
       buffer = newBuffer;
     }
     return buffer;
   }
   
   public static byte[] loadExact(InputStream in, int length) throws IOException {
     byte[] buffer = new byte[length];
     int offset = 0;
     for(;;) {
       int remain = length - offset;
       if(remain <= 0) {
         break;
       }
       int numRead = in.read(buffer, offset, remain);
       if(numRead == -1) {
         throw new IOException("Reached EOF, read " + offset + " expecting " + length);
       }
     offset += numRead;
     }
     return buffer;
   }
   public static boolean equalContent(File file, byte[] content) throws IOException {
     long length = file.length();
     if(length > Integer.MAX_VALUE) {
       throw new IOException("File "" + file + "" too big");
     }
     InputStream in = new FileInputStream(file);
     try {
       byte[] fileContent = loadExact(in, (int) length);
       return java.util.Arrays.equals(content, fileContent);
     } finally {
       in.close();
     }
   }
   
   public static void save(File file, byte[] content) throws IOException {
     FileOutputStream out = new FileOutputStream(file);
     try {
       out.write(content);
     } finally {
       out.close();
     }
   }
   
   /**
    * Reads line without buffering.
    */
   public static String readLine(InputStream in) throws IOException {
     int b;
     StringBuffer sb = null;
     OUTER:
     while((b = in.read()) != -1) {
       if(sb == null) {
         sb = new StringBuffer();
       }
       switch(b) {
         case (byte) "\n":
           break OUTER;
         case (byte) "\r":
           break;
         default:
           sb.append((char) b);
           break;
       }
     }
     return sb == null ? null : sb.toString();
   }
   
   public static void touch(File file) {
     file.setLastModified(System.currentTimeMillis());
   }
   
   public static void saveStrings(File file, java.util.Collection list) throws IOException {
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
     try {
       PrintWriter writer = new PrintWriter(bout);
       java.util.Iterator i = list.iterator();
       while(i.hasNext()) {
         String text = (String) i.next();
         writer.println(text);
       }
       writer.flush();
     } finally {
       bout.close();
     }
   }
   
   public static java.util.List loadStrings(File file) throws IOException {
     java.util.List list = new java.util.LinkedList();
     InputStream in = new FileInputStream(file);
     try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in));
       String line;
       while((line = reader.readLine()) != null) {
         list.add(line);
       }
       return list;
     } finally {
       in.close();
     }
   }
   

}</source>





Load file to byte array

   <source lang="java">

/******************************************************************

  • CyberUtil for Java
  • Copyright (C) Satoshi Konno 2002-2003
  • File: FileUtil.java
  • Revision:
  • 01/03/03
  • - first revision.
                                                                                                                                    • /

import java.io.*; public final class FileUtil {

 public final static byte[] load(String fileName)
 {
   try { 
     FileInputStream fin=new FileInputStream(fileName);
     return load(fin);
   }
   catch (Exception e) {

     return new byte[0];
   }
 }
 public final static byte[] load(File file)
 {
   try { 
     FileInputStream fin=new FileInputStream(file);
     return load(fin);
   }
   catch (Exception e) {
    
     return new byte[0];
   }
 }
 public final static byte[] load(FileInputStream fin)
 {
   byte readBuf[] = new byte[512*1024];
 
   try { 
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
   
     int readCnt = fin.read(readBuf);
     while (0 < readCnt) {
       bout.write(readBuf, 0, readCnt);
       readCnt = fin.read(readBuf);
     }
     
     fin.close();
     
     return bout.toByteArray();
   }
   catch (Exception e) {
    
     return new byte[0];
   }
 }
 

}</source>





Reads bytes available from one InputStream and returns these bytes in a byte array.

   <source lang="java">

import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main {

 /**
  * 
  * @param in The InputStream to read the bytes from.
  * @return A byte array containing the bytes that were read.
  * @throws IOException If I/O error occurred.
  */
 public static final byte[] readFully(InputStream in)
   throws IOException
 {
   ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
   transfer(in, out);
   out.close();
   return out.toByteArray();
 }
 /**
  * Transfers all bytes that can be read from in to out.
  *
  * @param in The InputStream to read data from.
  * @param out The OutputStream to write data to.
  * @return The total number of bytes transfered.
  */
 public static final long transfer(InputStream in, OutputStream out)
   throws IOException
 {
   long totalBytes = 0;
   int bytesInBuf = 0;
   byte[] buf = new byte[4096];
   while ((bytesInBuf = in.read(buf)) != -1) {
     out.write(buf, 0, bytesInBuf);
     totalBytes += bytesInBuf;
   }
   return totalBytes;
 }

}</source>





Return the specified class. Checks the ThreadContext classloader first, then uses the System classloader.

   <source lang="java">

/*

* Copyright  2003-2008 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.InputStream; /**

*
*  @author 
*  @version $Id: ClassUtils.java 685685 2008-08-13 21:43:27Z nbubna $
* @since 1.5
*/

public class Main {

 /**
  * Return the specified class.  Checks the ThreadContext classloader first,
  * then uses the System classloader.  Should replace all calls to
  * Class.forName( claz ) (which only calls the System class
  * loader) when the class might be in a different classloader (e.g. in a
  * webapp).
  *
  * @param clazz the name of the class to instantiate
  * @return the requested Class object
  * @throws ClassNotFoundException
  */
 public static Class getClass(String clazz) throws ClassNotFoundException
 {
     /**
      * Use the Thread context classloader if possible
      */
     ClassLoader loader = Thread.currentThread().getContextClassLoader();
     if (loader != null)
     {
         try
         {
             return Class.forName(clazz, true, loader);
         }
         catch (ClassNotFoundException E)
         {
             /**
              * If not found with ThreadContext loader, fall thru to
              * try System classloader below (works around bug in ant).
              */
         }
     }
     /**
      * Thread context classloader isn"t working out, so use system loader.
      */
     return Class.forName(clazz);
 }

}</source>





Translates between byte arrays and strings of "0"s and "1"s.

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

/**

* Translates between byte arrays and strings of "0"s and "1"s.
* 
* @todo may want to add more bit vector functions like and/or/xor/nand
* @todo also might be good to generate boolean[] from byte[] et. cetera.
* 
* @author Apache Software Foundation
* @since 1.3
* @version $Id $
*/

public class BinaryCodec {

 /*
  * tried to avoid using ArrayUtils to minimize dependencies while using these
  * empty arrays - dep is just not worth it.
  */
 /** Empty char array. */
 private static final char[] EMPTY_CHAR_ARRAY = new char[0];
 /** Empty byte array. */
 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
 /** Mask for bit 0 of a byte. */
 private static final int BIT_0 = 1;
 /** Mask for bit 1 of a byte. */
 private static final int BIT_1 = 0x02;
 /** Mask for bit 2 of a byte. */
 private static final int BIT_2 = 0x04;
 /** Mask for bit 3 of a byte. */
 private static final int BIT_3 = 0x08;
 /** Mask for bit 4 of a byte. */
 private static final int BIT_4 = 0x10;
 /** Mask for bit 5 of a byte. */
 private static final int BIT_5 = 0x20;
 /** Mask for bit 6 of a byte. */
 private static final int BIT_6 = 0x40;
 /** Mask for bit 7 of a byte. */
 private static final int BIT_7 = 0x80;
 private static final int[] BITS = { BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7 };
 /**
  * Converts an array of raw binary data into an array of ascii 0 and 1
  * characters.
  * 
  * @param raw
  *          the raw binary data to convert
  * @return 0 and 1 ascii character bytes one for each bit of the argument
  * @see org.apache.rumons.codec.BinaryEncoder#encode(byte[])
  */
 public byte[] encode(byte[] raw) {
   return toAsciiBytes(raw);
 }
 /**
  * Converts an array of raw binary data into an array of ascii 0 and 1 chars.
  * 
  * @param raw
  *          the raw binary data to convert
  * @return 0 and 1 ascii character chars one for each bit of the argument
  * @throws EncoderException
  *           if the argument is not a byte[]
  * @see org.apache.rumons.codec.Encoder#encode(java.lang.Object)
  */
 public Object encode(Object raw) throws RuntimeException {
   if (!(raw instanceof byte[])) {
     throw new RuntimeException("argument not a byte array");
   }
   return toAsciiChars((byte[]) raw);
 }
 /**
  * Decodes a byte array where each byte represents an ascii "0" or "1".
  * 
  * @param ascii
  *          each byte represents an ascii "0" or "1"
  * @return the raw encoded binary where each bit corresponds to a byte in the
  *         byte array argument
  * @throws DecoderException
  *           if argument is not a byte[], char[] or String
  * @see org.apache.rumons.codec.Decoder#decode(java.lang.Object)
  */
 public Object decode(Object ascii) throws RuntimeException {
   if (ascii == null) {
     return EMPTY_BYTE_ARRAY;
   }
   if (ascii instanceof byte[]) {
     return fromAscii((byte[]) ascii);
   }
   if (ascii instanceof char[]) {
     return fromAscii((char[]) ascii);
   }
   if (ascii instanceof String) {
     return fromAscii(((String) ascii).toCharArray());
   }
   throw new RuntimeException("argument not a byte array");
 }
 /**
  * Decodes a byte array where each byte represents an ascii "0" or "1".
  * 
  * @param ascii
  *          each byte represents an ascii "0" or "1"
  * @return the raw encoded binary where each bit corresponds to a byte in the
  *         byte array argument
  * @see org.apache.rumons.codec.Decoder#decode(Object)
  */
 public byte[] decode(byte[] ascii) {
   return fromAscii(ascii);
 }
 /**
  * Decodes a String where each char of the String represents an ascii "0" or
  * "1".
  * 
  * @param ascii
  *          String of "0" and "1" characters
  * @return the raw encoded binary where each bit corresponds to a byte in the
  *         byte array argument
  * @see org.apache.rumons.codec.Decoder#decode(Object)
  */
 public byte[] toByteArray(String ascii) {
   if (ascii == null) {
     return EMPTY_BYTE_ARRAY;
   }
   return fromAscii(ascii.toCharArray());
 }
 // ------------------------------------------------------------------------
 //
 // static codec operations
 //
 // ------------------------------------------------------------------------
 /**
  * Decodes a byte array where each char represents an ascii "0" or "1".
  * 
  * @param ascii
  *          each char represents an ascii "0" or "1"
  * @return the raw encoded binary where each bit corresponds to a char in the
  *         char array argument
  */
 public static byte[] fromAscii(char[] ascii) {
   if (ascii == null || ascii.length == 0) {
     return EMPTY_BYTE_ARRAY;
   }
   // get length/8 times bytes with 3 bit shifts to the right of the length
   byte[] l_raw = new byte[ascii.length >> 3];
   /*
    * We decr index jj by 8 as we go along to not recompute indices using
    * multiplication every time inside the loop.
    */
   for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) {
     for (int bits = 0; bits < BITS.length; ++bits) {
       if (ascii[jj - bits] == "1") {
         l_raw[ii] |= BITS[bits];
       }
     }
   }
   return l_raw;
 }
 /**
  * Decodes a byte array where each byte represents an ascii "0" or "1".
  * 
  * @param ascii
  *          each byte represents an ascii "0" or "1"
  * @return the raw encoded binary where each bit corresponds to a byte in the
  *         byte array argument
  */
 public static byte[] fromAscii(byte[] ascii) {
   if (ascii == null || ascii.length == 0) {
     return EMPTY_BYTE_ARRAY;
   }
   // get length/8 times bytes with 3 bit shifts to the right of the length
   byte[] l_raw = new byte[ascii.length >> 3];
   /*
    * We decr index jj by 8 as we go along to not recompute indices using
    * multiplication every time inside the loop.
    */
   for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) {
     for (int bits = 0; bits < BITS.length; ++bits) {
       if (ascii[jj - bits] == "1") {
         l_raw[ii] |= BITS[bits];
       }
     }
   }
   return l_raw;
 }
 /**
  * Converts an array of raw binary data into an array of ascii 0 and 1
  * character bytes - each byte is a truncated char.
  * 
  * @param raw
  *          the raw binary data to convert
  * @return an array of 0 and 1 character bytes for each bit of the argument
  * @see org.apache.rumons.codec.BinaryEncoder#encode(byte[])
  */
 public static byte[] toAsciiBytes(byte[] raw) {
   if (raw == null || raw.length == 0) {
     return EMPTY_BYTE_ARRAY;
   }
   // get 8 times the bytes with 3 bit shifts to the left of the length
   byte[] l_ascii = new byte[raw.length << 3];
   /*
    * We decr index jj by 8 as we go along to not recompute indices using
    * multiplication every time inside the loop.
    */
   for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) {
     for (int bits = 0; bits < BITS.length; ++bits) {
       if ((raw[ii] & BITS[bits]) == 0) {
         l_ascii[jj - bits] = "0";
       } else {
         l_ascii[jj - bits] = "1";
       }
     }
   }
   return l_ascii;
 }
 /**
  * Converts an array of raw binary data into an array of ascii 0 and 1
  * characters.
  * 
  * @param raw
  *          the raw binary data to convert
  * @return an array of 0 and 1 characters for each bit of the argument
  * @see org.apache.rumons.codec.BinaryEncoder#encode(byte[])
  */
 public static char[] toAsciiChars(byte[] raw) {
   if (raw == null || raw.length == 0) {
     return EMPTY_CHAR_ARRAY;
   }
   // get 8 times the bytes with 3 bit shifts to the left of the length
   char[] l_ascii = new char[raw.length << 3];
   /*
    * We decr index jj by 8 as we go along to not recompute indices using
    * multiplication every time inside the loop.
    */
   for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) {
     for (int bits = 0; bits < BITS.length; ++bits) {
       if ((raw[ii] & BITS[bits]) == 0) {
         l_ascii[jj - bits] = "0";
       } else {
         l_ascii[jj - bits] = "1";
       }
     }
   }
   return l_ascii;
 }
 /**
  * Converts an array of raw binary data into a String of ascii 0 and 1
  * characters.
  * 
  * @param raw
  *          the raw binary data to convert
  * @return a String of 0 and 1 characters representing the binary data
  * @see org.apache.rumons.codec.BinaryEncoder#encode(byte[])
  */
 public static String toAsciiString(byte[] raw) {
   return new String(toAsciiChars(raw));
 }

}</source>