Read a double from the byte array at the given offset. - Java java.lang

Java examples for java.lang:byte Array to double

Description

Read a double from 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;
        System.out.println(readDouble(array, offset));
    }/*from  w  ww. j  a va2  s. co  m*/

    /**
     * Read a double from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return data
     */
    public final static double readDouble(byte[] array, int offset) {
        return Double.longBitsToDouble(readLong(array, offset));
    }

    /**
     * Read a long from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return data
     */
    public final static long readLong(byte[] array, int offset) {
        // First make integers to resolve signed vs. unsigned issues.
        long b0 = array[offset + 0];
        long b1 = array[offset + 1] & 0xFF;
        long b2 = array[offset + 2] & 0xFF;
        long b3 = array[offset + 3] & 0xFF;
        long b4 = array[offset + 4] & 0xFF;
        int b5 = array[offset + 5] & 0xFF;
        int b6 = array[offset + 6] & 0xFF;
        int b7 = array[offset + 7] & 0xFF;
        return ((b0 << 56) + (b1 << 48) + (b2 << 40) + (b3 << 32)
                + (b4 << 24) + (b5 << 16) + (b6 << 8) + (b7 << 0));
    }
}

Related Tutorials