Get a byte array from a double. - Java java.lang

Java examples for java.lang:byte Array to double

Description

Get a byte array from a double.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        double d = 2.45678;
        System.out.println(java.util.Arrays.toString(double2bytes(d)));
    }//from   w w w . j  a v  a  2  s. co  m

    /**
     * Get a byte array from a double.
     * 
     * @param d double
     * @return a byte array
     */
    public static final byte[] double2bytes(double d) {
        byte[] b = { 0, 0, 0, 0, 0, 0, 0, 0 };
        double2bytes(d, b, 0);
        return b;
    }

    /**
     * Set a byte array at specific offset from a double.
     * 
     * @param d   double
     * @param b   byte array
     * @param off offset
     */
    public static void double2bytes(double d, byte[] b, int off) {
        long l = Double.doubleToLongBits(d);
        b[off + 7] = (byte) l;
        b[off + 6] = (byte) (l >>> 8);
        b[off + 5] = (byte) (l >>> 16);
        b[off + 4] = (byte) (l >>> 24);
        b[off + 3] = (byte) (l >>> 32);
        b[off + 2] = (byte) (l >>> 40);
        b[off + 1] = (byte) (l >>> 48);
        b[off + 0] = (byte) (l >>> 56);
    }
}

Related Tutorials