Get a byte array from a float. - Java java.lang

Java examples for java.lang:byte Array to float

Description

Get a byte array from a float.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        float f = 2.45678f;
        System.out.println(java.util.Arrays.toString(float2bytes(f)));
    }//from  w  ww . j av a  2 s . c om

    /**
     * Get a byte array from a float.
     * 
     * @param f float
     * @return a byte array
     */
    public static final byte[] float2bytes(float f) {
        byte[] b = { 0, 0, 0, 0 };
        float2bytes(f, b, 0);
        return b;
    }

    /**
     * Set a byte array at specific offset from a float.
     * 
     * @param f   float
     * @param b   byte array
     * @param off offset
     */
    public static void float2bytes(float f, byte[] b, int off) {
        int i = Float.floatToIntBits(f);
        b[off + 3] = (byte) i;
        b[off + 2] = (byte) (i >>> 8);
        b[off + 1] = (byte) (i >>> 16);
        b[off + 0] = (byte) (i >>> 24);
    }
}

Related Tutorials