Convert double value to reversed byte array. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert double value to reversed byte array.

Demo Code


//package com.java2s;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] argv) throws Exception {
        double value = 2.45678;
        System.out.println(java.util.Arrays
                .toString(doubleToReverseBytes(value)));
    }//from  w w  w  .  j a  va  2  s  . com

    /**
     * Convert double value to reversed byte array.
     */
    @Nonnull
    public static byte[] doubleToReverseBytes(double value) {
        return reverse(doubleToBytes(value));
    }

    /**
     * Reverse byte array
     */
    @Nullable
    public static byte[] reverse(@Nullable byte[] data) {
        if (data == null)
            return null;

        int length = data.length;
        byte[] result = new byte[length];
        if (length == 0)
            return result;

        for (int i = 0; i < length; i++) {
            result[i] = data[length - i - 1];
        }

        return result;
    }

    /**
     * Convert double value to byte array.
     */
    @Nonnull
    public static byte[] doubleToBytes(double value) {
        return ByteBuffer.allocate(Double.BYTES).putDouble(value).array();
    }
}

Related Tutorials