Android Float to Byte Array Convert floatToBytes(float value)

Here you can find the source of floatToBytes(float value)

Description

float To Bytes

Declaration

public static byte[] floatToBytes(float value) 

Method Source Code

//package com.java2s;

import java.nio.ByteBuffer;

public class Main {
    private static ByteBuffer int_buffer = ByteBuffer.allocate(4);

    public static byte[] floatToBytes(float value) {
        int iv = (int) value;
        byte[] values = intToBytes(iv);

        int fv = (int) ((value - iv) * 1000);
        if (fv < 0) {
            fv = 0 - fv;/*  w  w  w.  ja va 2s.c  om*/
        }
        values = append(values, intToBytes(fv));
        return values;
    }

    public static byte[] intToBytes(int x) {
        int_buffer = ByteBuffer.allocate(4);
        int_buffer.putInt(x);
        return subByte(int_buffer.array(), -2);
    }

    public static byte[] append(byte[] data, byte[] adata) {
        if (data == null) {
            data = new byte[0];
        }
        int len = data.length;
        if (adata == null) {
            return data;
        }
        int alen = adata.length;

        byte[] result = new byte[(len + alen)];

        for (int i = 0, j = 0; i < len + alen; i++) {
            if (i < len) {
                result[i] = data[i];
                continue;
            }
            result[i] = adata[j];
            j++;
        }

        return result;

    }

    /**
     * @param data
     * @param start
     * @param end
     * @return
     */
    public static byte[] subByte(byte[] data, int start, int end) {
        int len = data.length;
        if (start >= len || end <= start || end < 1) {
            return null;
        }
        byte[] result = new byte[(end - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            if (i < end) {
                result[j] = data[i];
            } else {
                break;
            }
        }
        return result;
    }

    public static byte[] subByte(byte[] data, int start) {
        int len = data.length;
        if (start >= len) {
            return null;
        }
        if (start < 0) {
            start = len + start;
            if (start < 0) {
                return null;
            }
        }
        byte[] result = new byte[(len - start)];
        for (int i = start, j = 0; i < len; i++, j++) {
            result[j] = data[i];
        }
        return result;
    }
}

Related

  1. FloatToByte(float f)
  2. float2bytesBE(float val, byte[] b, int off)
  3. float2bytesLE(float val, byte[] b, int off)
  4. floats2bytesBE(float[] val)
  5. floats2bytesLE(float[] val)
  6. getBytes(float data)