Thursday, May 31, 2012

Conversion of numeric primitives to byte array and vice verse

As I was so tired of every now and again to find out how to perform the conversion for different primitives, and then I found this, which is very good because it does the work, but annoying somewhat to over view, every conversion has its own method.

Me been me will not allow myself to write that much of a code for same functionality, I have two generic methods to do all the conversion work for me...

This method would convert any given numeric none floating, to byte array.


  /**
  * Converts any given numeric value which is not floating, to byte array. <br>
  * <br>
  * {@link Byte}<br>
  * {@link Short}<br>
  * {@link Integer}<br>
  * {@link Long}<br>
  *
  * @param _value The value to parse
  * @return A byte array of the supplied value.
  */
 public static byte[] toByteArray(Number _value) {
  int length;
  long value;
  if (_value instanceof Byte) {
   length = Byte.SIZE >> 3;
   value = (Byte) _value;
  } else if (_value instanceof Short) {
   length = Short.SIZE >> 3;
   value = (Short) _value;
  } else if (_value instanceof Integer) {
   length = Integer.SIZE >> 3;
   value = (Integer) _value;
  } else if (_value instanceof Long) {
   length = Long.SIZE >> 3;
   value = (Long) _value;
  } else
   throw new IllegalArgumentException(
     "Parameter must be one of the following types:\n Byte, Short, Integer, Long");
  byte[] byteArray = new byte[length];
  for (int i = 0; i < length; i++) {
   byteArray[i] = (byte) ((value >> (8 * (length - i - 1))) & 0xff);
  }
  return byteArray;
 }

  

This method would convert a byte array to a long value, according to the size of the array.


 /**
  * Converts a byte array, to a numeric value. <br>
  * <br>
  * {@link Byte}<br>
  * {@link Short}<br>
  * {@link Integer}<br>
  * {@link Long}<br>
  *
  * @param byteArray The byte array with the value to parse.
  * @return The value which rests within the supplied byte array
  */
 public static long fromByteArray(byte[] byteArray) {
  int length = byteArray.length;
  long value = 0;

  if (length > 8)
   throw new IllegalArgumentException("Array parameter length==" + byteArray.length + ". MUST be length <= 8");

  for (int i = 0; i < length; i++) {
   value |= ((0xffL & byteArray[i]) << (8 * (length - i - 1)));
  }
  return value;
 }


If you have found this useful, +1 this...


As discussed here, perhaps I should have mentioned that this is a quick generic unified access to the conversion function, that SHOULD not be used with crazy ass repetitive loops...

No comments:

Post a Comment