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

Java examples for java.lang:byte Array Convert

Description

Convert byte array to reversed double value.

Demo Code


//package com.java2s;

import javax.annotation.Nullable;
import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] value = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(reverseBytesToDouble(value));
    }/*from w  w  w. j  a v a 2 s. c om*/

    /**
     * Convert byte array to reversed double value.
     */
    public static double reverseBytesToDouble(@Nullable byte[] value) {
        return bytesToDouble(reverse(value));
    }

    /**
     * Convert byte array to double value.
     */
    public static double bytesToDouble(@Nullable byte[] value) {
        if (value == null)
            return Double.NaN;
        if (value.length != Double.BYTES)
            throw new IllegalArgumentException("value length is not double");

        return ByteBuffer.allocate(Double.BYTES).put(value).getDouble(0);
    }

    /**
     * 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;
    }
}

Related Tutorials