Converts an array of bytes to a float. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts an array of bytes to a float.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte data = 2;
        System.out.println(bytesToFloat(data));
    }//from w w  w . j av  a  2s  .c o  m

    /**
     * <p>
     * Converts an array of bytes to a float. If there are more than four bytes, the first four bytes in the array are used and the
     * rest are ignored.<br>
     * There is no error checking done, so please ensure the byte array contains at least four elements.
     * </p>
     * 
     * @param data
     *            The byte array to be converted to a float.
     * @return The float equivalent of the given byte array.
     */
    public static float bytesToFloat(byte... data) {
        return (Float.intBitsToFloat((data[3] & 0xFF) << 24
                | (data[2] & 0xFF) << 16 | (data[1] & 0xFF) << 8 | data[0]
                & 0xFF));
    }
}

Related Tutorials