Mega Code Archive

 
Categories / Android / Date Type
 

Byte Converter

//package net.capstone.cra.smartcontroller.util; /**  * The Class ByteConverter.  */ class ByteConverter {   /**    * Int2byte.    * integer type convert to byte type    *     * @param i the i    * @return the byte[]    */   public static byte[] int2byte(int i) {     byte[] array = new byte[4];     array[3] = (byte) (i & 0xff);     array[2] = (byte) ((i >> 8) & 0xff);     array[1] = (byte) ((i >> 16) & 0xff);     array[0] = (byte) ((i >> 24) & 0xff);     return array;   }   /**    * Byte2int.    * byte type convert to integer type.    *    * @param bytes the bytes    * @param start the start    * @return the int    */   public static int byte2int(byte[] bytes, int start) {     int newValue = 0;        newValue |= (((int) bytes[start + 0]) << 24) & 0xFF000000;     newValue |= (((int) bytes[start + 1]) << 16) & 0xFF0000;     newValue |= (((int) bytes[start + 2]) << 8) & 0xFF00;     newValue |= (((int) bytes[start + 3])) & 0xFF;        return newValue;   }   /**    * Float2bytes.    * float type convert to byte type.     *    * @param value the value    * @return the byte[]    */   public static byte[] float2bytes(float value) {        byte[] array = new byte[4];     int intBits = Float.floatToIntBits(value);        array[0] = (byte) ((intBits & 0x000000ff) >> 0);     array[1] = (byte) ((intBits & 0x0000ff00) >> 8);     array[2] = (byte) ((intBits & 0x00ff0000) >> 16);     array[3] = (byte) ((intBits & 0xff000000) >> 24);        return array;   }   /**    * Byte2float.    * byte type convert to float type    *    * @param arr the arr    * @param start the start    * @return the float    */   public static float byte2float(byte[] arr, int start) {     int i = 0;     int len = 4;     int cnt = 0;     byte[] tmp = new byte[len];        for (i = start; i < (start + len); i++) {       tmp[cnt] = arr[i];       cnt++;     }        int accum = 0;     i = 0;     for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) {       accum |= ((long) (tmp[i] & 0xff)) << shiftBy;       i++;     }     return Float.intBitsToFloat(accum);   } }