Write a float to the byte array at the given offset. - Java java.lang

Java examples for java.lang:byte Array to float

Description

Write a float to 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;
        float v = 2.45678f;
        writeFloat(array, offset, v);//ww  w . j  a  v a  2s.  c  o m
    }

    /**
     * Write a float to the byte array at the given offset.
     * 
     * @param array Array to write to
     * @param offset Offset to write to
     * @param v data
     */
    public final static void writeFloat(byte[] array, int offset, float v) {
        writeInt(array, offset, Float.floatToIntBits(v));
    }

    /**
     * Write an integer to the byte array at the given offset.
     * 
     * @param array Array to write to
     * @param offset Offset to write to
     * @param v data
     */
    public final static void writeInt(byte[] array, int offset, int v) {
        array[offset + 0] = (byte) (v >>> 24);
        array[offset + 1] = (byte) (v >>> 16);
        array[offset + 2] = (byte) (v >>> 8);
        array[offset + 3] = (byte) (v >>> 0);
    }
}

Related Tutorials