Convert byte array to Integer and Long : Array Convert « Collections Data Structure « Java






Convert byte array to Integer and Long

    

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


public class Utils {


  public static void putInt(int value, byte[] array, int offset) {
    array[offset]   = (byte)(0xff & (value >> 24));
    array[offset+1] = (byte)(0xff & (value >> 16));
    array[offset+2] = (byte)(0xff & (value >> 8));
    array[offset+3] = (byte)(0xff & value);
  }

  public static int getInt(byte[] array, int offset) {
    return
      ((array[offset]   & 0xff) << 24) |
      ((array[offset+1] & 0xff) << 16) |
      ((array[offset+2] & 0xff) << 8) |
       (array[offset+3] & 0xff);
  }

  public static void putLong(long value, byte[] array, int offset) {
    array[offset]   = (byte)(0xff & (value >> 56));
    array[offset+1] = (byte)(0xff & (value >> 48));
    array[offset+2] = (byte)(0xff & (value >> 40));
    array[offset+3] = (byte)(0xff & (value >> 32));
    array[offset+4] = (byte)(0xff & (value >> 24));
    array[offset+5] = (byte)(0xff & (value >> 16));
    array[offset+6] = (byte)(0xff & (value >> 8));
    array[offset+7] = (byte)(0xff & value);
  }

  public static long getLong(byte[] array, int offset) {
    return
      ((long)(array[offset]   & 0xff) << 56) |
      ((long)(array[offset+1] & 0xff) << 48) |
      ((long)(array[offset+2] & 0xff) << 40) |
      ((long)(array[offset+3] & 0xff) << 32) |
      ((long)(array[offset+4] & 0xff) << 24) |
      ((long)(array[offset+5] & 0xff) << 16) |
      ((long)(array[offset+6] & 0xff) << 8) |
      ((long)(array[offset+7] & 0xff));
  }


}

   
    
    
    
  








Related examples in the same category

1.Convert array to string
2.Return a new byte array containing a sub-portion of the source array
3.byte array to int array
4.int array to byte array
5.Turn an array of ints into a printable string.
6.Array Converter
7.Convert array to string (from c3p0)
8.Convert byte array to string
9.Converts a Array to an Enumeration and allows it to be serializedConverts a Array to an Enumeration and allows it to be serialized
10.Array helper
11.Return a String representation of the given two-dimensional object array
12.Return a string representation of the given native two-dimensional long array.
13.Concatenates the given int[] array into one String, inserting a delimiter between each pair of elements.
14.Concatenates the given long[] array into one String, inserting a delimiter between each pair of elements.
15.Converts an array of Strings to a comma-sperated-list.