Byte-Array Conversion Utility Functions : Byte Array « File Input Output « Java






Byte-Array Conversion Utility Functions

       



import java.io.UnsupportedEncodingException;

/**
 * <p>Byte-Array Conversion Utility Functions.</p>
 *
 * $Id: ByteUtils.java,v 1.6 2005/06/16 19:58:58 mokhov Exp $
 *
 * @version $Revision: 1.6 $
 * @author Serguei Mokhov
 * @since 0.3.0
 */
public class ByteUtils
{
  /**
   * Allow derivatives.
   */
  protected ByteUtils()
  {
  }

  /**
   * Converts a byte array to short value.
   * Equivalent to byteArrayToShort(paRawBytes, 0, pbBigEndian);
   *
   * @param paRawBytes the byte array
   * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
   *
   * @return short representation of the bytes
   */
  public static short byteArrayToShort(byte[] paRawBytes, boolean pbBigEndian)
  {
    return byteArrayToShort(paRawBytes, 0, pbBigEndian);
  }

  /**
   * Converts a portion of a byte array with given offset to short value.
   *
   * @param paRawBytes the byte array
   * @param piOffset offset in the original array to start reading bytes from
   * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
   *
   * @return short representation of the bytes
   */
  public static short byteArrayToShort(byte[] paRawBytes, int piOffset, boolean pbBigEndian)
  {
    int iRetVal = -1;

    // TODO: revisit this: should we silently add missing byte and should
    // we ingnore excessing bytes?
    if(paRawBytes.length < piOffset + 2)
      return -1;

    int iLow;
    int iHigh;

    if(pbBigEndian)
    {
      iLow  = paRawBytes[piOffset + 1];
      iHigh = paRawBytes[piOffset + 0];
    }
    else
    {
      iLow  = paRawBytes[piOffset + 0];
      iHigh = paRawBytes[piOffset + 1];
    }

    // Merge high-order and low-order byte to form a 16-bit double value.
    iRetVal = (iHigh << 8) | (0xFF & iLow);

    return (short)iRetVal;
  }

  /**
   * Converts a byte array to int value.
   * Equivalent to intArrayToShort(paRawBytes, 0, pbBigEndian);
   *
   * @param paRawBytes the byte array
   * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
   *
   * @return int representation of the bytes
   */
  public static int byteArrayToInt(byte[] paRawBytes, boolean pbBigEndian)
  {
    return byteArrayToInt(paRawBytes, 0, pbBigEndian);
  }

  /**
   * Converts a portion of a byte array with given offset to int value.
   *
   * @param paRawBytes the byte array
   * @param piOffset offset in the original array to start reading bytes from
   * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
   *
   * @return int representation of the bytes
   */
  public static int byteArrayToInt(byte[] paRawBytes, int piOffset, boolean pbBigEndian)
  {
    int iRetVal = -1;

    if(paRawBytes.length < piOffset + 4)
      return iRetVal;

    int iLowest;
    int iLow;
    int iMid;
    int iHigh;

    if(pbBigEndian)
    {
      iLowest = paRawBytes[piOffset + 3];
      iLow    = paRawBytes[piOffset + 2];
      iMid    = paRawBytes[piOffset + 1];
      iHigh   = paRawBytes[piOffset + 0];
    }
    else
    {
      iLowest = paRawBytes[piOffset + 0];
      iLow    = paRawBytes[piOffset + 1];
      iMid    = paRawBytes[piOffset + 2];
      iHigh   = paRawBytes[piOffset + 3];
    }

    // Merge four bytes to form a 32-bit int value.
    iRetVal = (iHigh << 24) | (iMid << 16) | (iLow << 8) | (0xFF & iLowest);

    return iRetVal;
  }

  /**
   * Converts an int value to a byte array.
   *
   * @param piValueToConvert the original integer
   * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
   *
   * @return byte[] representation of the int
   */
  public static byte[] intToByteArray(int piValueToConvert, boolean pbBigEndian)
  {
    byte[] aRetVal = new byte[4];

    byte iLowest;
    byte iLow;
    byte iMid;
    byte iHigh;

    iLowest = (byte)(piValueToConvert & 0xFF);
    iLow    = (byte)((piValueToConvert >> 8) & 0xFF);
    iMid    = (byte)((piValueToConvert >> 16) & 0xFF);
    iHigh   = (byte)((piValueToConvert >> 24) & 0xFF);

    if(pbBigEndian)
    {
      aRetVal[3] = iLowest;
      aRetVal[2] = iLow;
      aRetVal[1] = iMid;
      aRetVal[0] = iHigh;
    }
    else
    {
      aRetVal[0] = iLowest;
      aRetVal[1] = iLow;
      aRetVal[2] = iMid;
      aRetVal[3] = iHigh;
    }

    return aRetVal;
  }

  /**
   * Converts a byte array to String value.
   * Cleans up non-word characters along the way.
   *
   * Equivalent to byteArrayToString(paRawBytes, 0, paRawBytes.length);
   *
   * @param paRawBytes the byte array, non-UNICODE
   *
   * @return UNICODE String representation of the bytes
   */
  public static String byteArrayToString(byte[] paRawBytes)
  {
    return byteArrayToString(paRawBytes, 0, paRawBytes.length);
  }

  /**
   * Converts a portion of a byte array to String value.
   * Cleans up non-word characters along the way.
   *
   * @param paRawBytes the byte array, non-UNICODE
   * @param piOffset offset in the original array to start reading bytes from
   * @param piLength how many bytes of the array paramter to interpret as String
   *
   * @return UNICODE String representation of the bytes with trailing garbage stripped;
   *         "" if array length is less than piOffset + piLength;
   *         "" if the generatied string begins with garbage
   */
  public static String byteArrayToString(byte[] paRawBytes, int piOffset, int piLength)
  {
    if(paRawBytes.length < piOffset + piLength)
      return "";

    String oBeautifulString = new String(paRawBytes, piOffset, piLength);
    int i = 0;

    if(oBeautifulString.matches("^\\W") == true)
      oBeautifulString = "";
    else
    {
      for(i = piOffset; i < piOffset + piLength; i++)
      {
        if(paRawBytes[i] < 32 || paRawBytes[i] > 128)
          break;
      }

      oBeautifulString = oBeautifulString.substring(0, i - piOffset);
    }

    return oBeautifulString;
  }

  /**
   * Converts a String value to a byte array in US-ASCII charset.
   *
   * Equivalent to stringToByteArray(pstrStringToConvert, "US-ASCII");
   *
   * @param pstrStringToConvert the original string
   *
   * @return null-terminated byte[] representation of the String
   */
  public static byte[] stringToByteArray(String pstrStringToConvert)
  {
    return stringToByteArray(pstrStringToConvert, "US-ASCII");
  }

  /**
   * Attempts to convert a String value to a byte array in specified charset.
   * If the charset is invalid, returns plain byte-representation of the host environment.
   *
   * @param pstrStringToConvert the original string
   * @param pstrCharSet characted set to assume for the original string
   *
   * @return null-terminated byte[] representation of the String
   */
  public static byte[] stringToByteArray(String pstrStringToConvert, String pstrCharSet)
  {
    byte[] aRecordData = null;

    try
    {
      aRecordData = (pstrStringToConvert + '\0').getBytes(pstrCharSet);
    }
    catch(UnsupportedEncodingException e)
    {
      System.err.println("WARNING: " + e);
      aRecordData = (pstrStringToConvert + '\0').getBytes();
    }

    return aRecordData;
  }
    /**
   * Returns source code revision information.
   * @return revision string
   */
  public static String getMARFSourceCodeRevision()
  {
    return "$Revision: 1.6 $";
  }
}

// EOF

   
    
    
    
    
    
    
  








Related examples in the same category

1.Load file to byte array
2.Manages fixed-length byte arrays
3.ByteArray wraps java byte arrays (byte[]) to allow byte arrays to be used as keys in hashtables.
4.Returns a object from the given byte array.
5.Load File as byte array
6.Gets an array of bytes corresponding to the given object
7.An implementation of a virtual file, whose contents are kept in memory
8.Given a hexstring this will return the byte array corresponding to string
9.Decode byte array
10.Compare two byte[] for differences, either may be null
11.Convert the bytes within the specified range of the given byte array into a String
12.Convert the bytes within the specified range of the given byte array into a signed integer
13.Convert the bytes within the specified range of the given byte array into a signed integer in the given radix
14.Convert the bytes within the specified range of the given byte array into a signed long
15.Converts a byte array into a hexadecimal string
16.Converts a byte array into hexadecimal characters which are written as ASCII to the given output stream.
17.Convert byte array into a printable format: a String of hexadecimal digit characters (two per byte).
18.Convert hexadecimal digits into byte array by encoding each two hexadecimal digits as a byte.
19.Get Hex from byte arrayGet Hex from byte array
20.Read file to byte array
21.Invert the endianness of words (4 bytes) in the given byte array starting at the given offset and repeating length/4 times.
22.Returns a hexadecimal representation of the given byte array.
23.Converts a hex string representation to a byte array.
24.extracts floats from byte array
25.Extracts ints from byte array
26.extracts longs from byte array
27.Extracts short ints from byte array
28.writes doubles to byte array
29.writes floats to byte array
30.writes ints to byte array
31.writes longs to byte array
32.writes short ints to byte array
33.Convert a string of hex digits to a byte array, with the first byte in the array being the MSB.
34.Byte Array
35.This class provides encoding of byte arrays into Base64-encoded strings, and decoding the other way.
36.Byte Array for Android
37.Convert byte array to Hex string
38.implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.
39.Convert a TCP/IP address string into a byte array
40.Read file to byte array and save byte array to file
41.Convert object to byte array and convert byte array to object
42.Byte ArrayList
43.converts an int integer array to a byte array.
44.Compress byte array
45.Utility method to convert byte array to hex-encoded string.
46.InputStream to String and Byte array
47.Fast Byte Array InputStream
48.Fast Byte Array OutputStream