Write the given double value into the buffer, starting at the offset value. - Java java.nio

Java examples for java.nio:DoubleBuffer

Description

Write the given double value into the buffer, starting at the offset value.

Demo Code

/*//w  w  w. j  a v a  2s .  c  o  m
 *   Copyright 2012 The Portico Project
 *
 *   This file is part of portico.
 *
 *   portico is free software; you can redistribute it and/or modify
 *   it under the terms of the Common Developer and Distribution License (CDDL) 
 *   as published by Sun Microsystems. For more information see the LICENSE file.
 *   
 *   Use of this software is strictly AT YOUR OWN RISK!!!
 *   If something bad happens you do not have permission to come crying to me.
 *   (that goes for your lawyer as well)
 *
 */

public class Main{

    /**
     * Write the given double value into the buffer, starting at the offset value.
     * <p/>
     * If there are less than 8 bytes from the offset to the length of the array, a
     * {@link BufferOverflowException} will be thrown for the buffer overflow.
     */
    public static void putDoubleBE(double value, byte[] buffer, int offset) {
        checkOverflow(8, buffer, offset);

        long rawbits = Double.doubleToLongBits(value);
        buffer[offset] = (byte) (rawbits >>> 56);
        buffer[offset + 1] = (byte) (rawbits >>> 48);
        buffer[offset + 2] = (byte) (rawbits >>> 40);
        buffer[offset + 3] = (byte) (rawbits >>> 32);
        buffer[offset + 4] = (byte) (rawbits >>> 24);
        buffer[offset + 5] = (byte) (rawbits >>> 16);
        buffer[offset + 6] = (byte) (rawbits >>> 8);
        buffer[offset + 7] = (byte) (rawbits >>> 0);
    }
    /**
     * Check that the required number of bytes are present in the array, starting from
     * the provided offset. If not, throw a {@link BufferOverflowException}.
     * 
     * @param required The number of bytes we expect to write
     * @param buffer The buffer to check
     * @param offset The offset to start from
     */
    public static void checkOverflow(int required, byte[] buffer, int offset)
            throws BufferOverflowException {
        int length = buffer.length - offset;
        if (length < required) {
            throw new BufferOverflowException(
                    "Buffer overflow. Tried to write " + required
                            + " bytes to buffer, only " + length
                            + " bytes available");
        }
    }
}

Related Tutorials