Java ByteOrder longToBytes(long longValue, ByteOrder byteOrder, boolean isSigned)

Here you can find the source of longToBytes(long longValue, ByteOrder byteOrder, boolean isSigned)

Description

Convert the provided longValue to a byte array of size 8.

License

Apache License

Parameter

Parameter Description
longValue a parameter
byteOrder a parameter

Declaration

private static byte[] longToBytes(long longValue, ByteOrder byteOrder, boolean isSigned) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.ByteOrder;

public class Main {
    public final static int BITS_PER_BYTE = 8;
    private final static int BYTES_IN_A_LONG = 8;

    /**//from www.j  a  va2  s  . co  m
     * Convert the provided longValue to a byte array of size 8.
     * 
     * @param longValue
     * @param byteOrder
     * @return
     */
    private static byte[] longToBytes(long longValue, ByteOrder byteOrder, boolean isSigned) {
        byte[] result = new byte[BYTES_IN_A_LONG];

        if (longValue < 0 && !isSigned) {
            throw new IllegalStateException(
                    "Cannot represent the negative value[" + longValue + "] in an unsigned byte array.");
        }

        if (byteOrder == ByteOrder.BIG_ENDIAN) {
            for (int i = BYTES_IN_A_LONG - 1; i >= 0; i--) {
                result[i] = (byte) (longValue & 0xFF);
                longValue >>= BITS_PER_BYTE;
            }
        } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
            for (int i = 0; i < BYTES_IN_A_LONG; i++) {
                result[i] = (byte) (longValue & 0xFF);
                longValue >>= BITS_PER_BYTE;
            }
        } else {
            throw new IllegalStateException("Unrecognized ByteOrder value[" + byteOrder + "].");
        }
        return result;
    }
}

Related

  1. getLong(byte[] b, int start, int end, ByteOrder byteOrder)
  2. getMostSignificantByte(byte[] bytes, ByteOrder byteOrder)
  3. getUnsignedShort(final int offset, final byte[] buffer, final ByteOrder byteOrder)
  4. increaseNumberOfBytes(byte[] originalBytes, int desiredNumberOfBytes, ByteOrder byteOrder, boolean isSigned)
  5. isNegative(byte[] bytes, ByteOrder byteOrder, boolean isSigned)
  6. opposite(ByteOrder order)
  7. reduceToSmallestByteArray(byte[] originalBytes, ByteOrder byteOrder, boolean isSigned)
  8. setLong(byte[] bytes, int start, int end, long value, ByteOrder byteOrder)
  9. toBytes(int value, ByteOrder order)