Read a float from the byte array at the given offset. - Java java.lang

Java examples for java.lang:byte Array to float

Description

Read a float from the byte array at the given offset.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        System.out.println(readFloat(array, offset));
    }/*from  w ww  .j  ava2s.  co m*/

    /**
     * Read a float from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return data
     */
    public final static float readFloat(byte[] array, int offset) {
        return Float.intBitsToFloat(readInt(array, offset));
    }

    /**
     * Read an integer from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return data
     */
    public final static int readInt(byte[] array, int offset) {
        // First make integers to resolve signed vs. unsigned issues.
        int b0 = array[offset + 0] & 0xFF;
        int b1 = array[offset + 1] & 0xFF;
        int b2 = array[offset + 2] & 0xFF;
        int b3 = array[offset + 3] & 0xFF;
        return ((b0 << 24) + (b1 << 16) + (b2 << 8) + (b3 << 0));
    }
}

Related Tutorials