Convert byte array to float - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert byte array to float

Demo Code

/**//from w  w w.j  a  v a 2 s .  co  m
 * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either version
 * 3 of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Plublic License along with this program;
 * if not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toFloat(data));
    }

    /**
     * Convert byte array to float
     * 
     * @param data - the byte array
     * @return the float value
     */
    public static float toFloat(byte[] data) {
        if (data == null || data.length != 4)
            return 0x0;
        return Float.intBitsToFloat(toInt(data));
    }

    /**
     * Convert byte array to int
     * 
     * @param data - the byte array
     * @return the int value
     */
    public static int toInt(byte[] data) {
        if (data == null || data.length != 4)
            return 0x0;
        // @formatter:off
        return (int) ((0xff & data[0]) << 24 | (0xff & data[1]) << 16
                | (0xff & data[2]) << 8 | (0xff & data[3]) << 0);
        // @formatter:on
    }
}

Related Tutorials