Java Long to Byte Array long2byteArray(final long number, final int length, final boolean swapHalfWord)

Here you can find the source of long2byteArray(final long number, final int length, final boolean swapHalfWord)

Description

Converts a long number to a byte array Halfwords can be swapped by setting swapHalfWord=true.

License

Apache License

Parameter

Parameter Description
number the input long number to be converted
length The length of the returned array
swapHalfWord Swap halfwords ([0][1][2][3]->[1][0][3][2])

Exception

Parameter Description
UnsupportedOperationException if the length is not a positive multiple of two

Return

The long value

Declaration

static byte[] long2byteArray(final long number, final int length, final boolean swapHalfWord) 

Method Source Code

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

public class Main {
    /**//from   w  w  w. jav a 2s  .  co m
     * Converts a long number to a byte array
     * Halfwords can be swapped by setting swapHalfWord=true.
     *
     * @param number       the input long number to be converted
     * @param length       The length of the returned array
     * @param swapHalfWord Swap halfwords ([0][1][2][3]->[1][0][3][2])
     * @return The long value
     * @throws UnsupportedOperationException if the length is not a positive multiple of two
     */
    static byte[] long2byteArray(final long number, final int length, final boolean swapHalfWord) {
        byte[] ret = new byte[length];
        int pos = 0;
        long tmp_number = 0;

        if (length % 2 != 0 || length < 2) {
            throw new UnsupportedOperationException();
        }

        tmp_number = number;
        for (pos = length - 1; pos >= 0; pos--) {
            ret[pos] = (byte) (tmp_number & 0xFF);
            tmp_number >>= 8;
        }

        if (!swapHalfWord) {
            byte tmp = 0;
            for (pos = 0; pos < length; pos++) {
                tmp = ret[pos];
                ret[pos++] = ret[pos];
                ret[pos] = tmp;
            }
        }

        return ret;
    }
}

Related

  1. long2byteArray(long k, byte b[], int off)
  2. long2ByteArray(long l)
  3. long2ByteArray(long srcValue, int len)
  4. long2ByteLE(byte[] bytes, long value, int offset)