Convert a double to a byte array. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert a double to a byte array.

Demo Code

/*/*from  w  ww .j ava  2s  .co m*/
 * @(#) ByteArrayUtils.java
 *
 * This code is part of the JAviator project: javiator.cs.uni-salzburg.at
 * Copyright (c) 2009  Clemens Krainer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
//package com.java2s;

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        double d = 2.45678;
        System.out.println(java.util.Arrays.toString(double2bytes(d)));
    }

    /**
     * Convert a double to a byte array.
     * 
     * @param d the double number to be converted.
     * @return the double represented as a byte array.
     * @throws IOException thrown in case of conversion errors.
     */
    public static byte[] double2bytes(double d) throws IOException {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DataOutputStream dOut = new DataOutputStream(bOut);
        dOut.writeDouble(d);
        return bOut.toByteArray();
    }
}

Related Tutorials