Android Byte Array to Float Convert bytesToFloat(byte[] bytes)

Here you can find the source of bytesToFloat(byte[] bytes)

Description

bytes To Float

Declaration

public static float bytesToFloat(byte[] bytes) 

Method Source Code

//package com.java2s;

public class Main {
    public static float bytesToFloat(byte[] bytes) {
        if (bytes == null) {
            return 0f;
        }//from   ww w. ja v a 2  s  .c o m
        int value1 = byte2Integer(subByte(bytes, 0, 2));
        int value2 = byte2Integer(subByte(bytes, 2));
        int rv = Math.round((float) value2 / 100);
        float rvf = rv / 10.0f;
        if (value1 < 0) {
            rvf = value1 - rvf;
        } else {
            rvf = rvf + value1;
        }
        return rvf;
    }

    public static Integer byte2Integer(byte bin) {
        return (Integer) (bin & 0xFF);

    }

    public static Integer byte2Integer(byte[] bin) {
        int mask = 0xff;
        int temp = 0;
        int n = 0;
        int size = bin.length;
        if (size <= 0) {
            return 0;
        }
        if (size < 2 && size > 0) {
            return byte2Integer(bin[0]);
        }

        for (int i = 0; i < bin.length; i++) {
            n <<= 8;
            temp = bin[i] & mask;
            n |= temp;
        }
        return n;
    }

    /**
     * @param data
     * @param start
     * @param end
     * @return
     */
    public static byte[] subByte(byte[] data, int start, int end) {
        int len = data.length;
        if (start >= len || end <= start || end < 1) {
            return null;
        }
        byte[] result = new byte[(end - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            if (i < end) {
                result[j] = data[i];
            } else {
                break;
            }
        }
        return result;
    }

    public static byte[] subByte(byte[] data, int start) {
        int len = data.length;
        if (start >= len) {
            return null;
        }
        if (start < 0) {
            start = len + start;
            if (start < 0) {
                return null;
            }
        }
        byte[] result = new byte[(len - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            result[j] = data[i];
        }
        return result;
    }
}

Related

  1. bytesBE2floats(byte[] b)
  2. bytesBE2floats2doubles(byte[] b)
  3. bytesLE2float(byte[] b, int off)
  4. bytesLE2floats(byte[] b)
  5. bytesLE2floats2doubles(byte[] b)
  6. bytesToFloat(byte[] bytes, int start)
  7. getFloat(byte[] b, int index)
  8. getFloat(byte[] buf, boolean bigEndian)
  9. getFloat(byte[] bytes)