Get a float from 4 bytes of the given array. - Java java.lang

Java examples for java.lang:byte Array to float

Description

Get a float from 4 bytes of the given array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(bytes2float(b));
    }/*  w w w.j  a v  a  2 s  .  c  om*/

    /**
     * Get a float from 4 bytes of the given array.
     * 
     * @param b byte array.
     * @return a float.
     */
    public static float bytes2float(byte[] b) {
        return bytes2float(b, 0);
    }

    /**
     * Get a float from 4 bytes of the given array at specific offset.
     * 
     * @param b byte array.
     * @param off offset.
     * @return a float.
     */
    public static float bytes2float(byte[] b, int off) {
        int i = b[off] << 24 | (b[off + 1] & 0xff) << 16
                | (b[off + 2] & 0xff) << 8 | (b[off + 3] & 0xff);
        return Float.intBitsToFloat(i);
    }
}

Related Tutorials