Java Long to Byte Array longToByteArray(long value, byte[] buffer, int offset)

Here you can find the source of longToByteArray(long value, byte[] buffer, int offset)

Description

Take the given long value and convert it into a byte array suitable for sending over the network.

License

Open Source License

Return

The number of bytes written

Declaration

public static final long longToByteArray(long value, byte[] buffer, int offset) 

Method Source Code

//package com.java2s;
/*/*from   www. ja va 2s  .  co m*/
 *   Copyright 2010 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 {
    /**
     * Take the given long value and convert it into a byte array suitable for sending over the
     * network. This data is written into the provided buffer. If there is not enough room in
     * the buffer, a RuntimeException will be thrown.
     * 
     * @return The number of bytes written
     */
    public static final long longToByteArray(long value, byte[] buffer, int offset) {
        if ((buffer.length - offset) < 8) {
            throw new RuntimeException("Not enough space in buffer to write long. Expected at "
                    + "least 8-bytes, found " + (buffer.length - offset));
        }

        buffer[offset] = (byte) ((value >> 56) & 0xff);
        buffer[offset + 1] = (byte) ((value >> 48) & 0xff);
        buffer[offset + 2] = (byte) ((value >> 40) & 0xff);
        buffer[offset + 3] = (byte) ((value >> 32) & 0xff);
        buffer[offset + 4] = (byte) ((value >> 24) & 0xff);
        buffer[offset + 5] = (byte) ((value >> 16) & 0xff);
        buffer[offset + 6] = (byte) ((value >> 8) & 0xff);
        buffer[offset + 7] = (byte) ((value >> 0) & 0xff);

        return 8;
    }
}

Related

  1. longToByteArray(long source)
  2. longToByteArray(long v)
  3. longToByteArray(long value)
  4. longToByteArray(long value)
  5. longToByteArray(long value)
  6. longToByteArray(long value, byte[] byteArray)
  7. longToByteArray(long value, byte[] data, int offset)
  8. longToByteArray(long value, byte[] dest)
  9. longToByteArray(long value, int nrOfBytes)