Java Convert via ByteBuffer longToBytesNoLeadZeroes(long val)

Here you can find the source of longToBytesNoLeadZeroes(long val)

Description

Converts a long value into a byte array.

License

Open Source License

Parameter

Parameter Description
val - long value to convert

Return

decimal value with leading byte that are zeroes striped

Declaration

public static byte[] longToBytesNoLeadZeroes(long val) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

public class Main {
    public static final byte[] ZERO_BYTE_ARRAY = new byte[] { 0 };

    /**// www .j  av a2 s . c  o  m
     * Converts a long value into a byte array.
     *
     * @param val - long value to convert
     * @return decimal value with leading byte that are zeroes striped
     */
    public static byte[] longToBytesNoLeadZeroes(long val) {

        // todo: improve performance by while strip numbers until (long >> 8 == 0)
        byte[] data = ByteBuffer.allocate(8).putLong(val).array();

        return stripLeadingZeroes(data);
    }

    public static byte[] stripLeadingZeroes(byte[] data) {

        if (data == null)
            return null;

        final int firstNonZero = firstNonZeroByte(data);
        switch (firstNonZero) {
        case -1:
            return ZERO_BYTE_ARRAY;

        case 0:
            return data;

        default:
            byte[] result = new byte[data.length - firstNonZero];
            System.arraycopy(data, firstNonZero, result, 0, data.length - firstNonZero);

            return result;
        }
    }

    public static int firstNonZeroByte(byte[] data) {
        for (int i = 0; i < data.length; ++i) {
            if (data[i] != 0) {
                return i;
            }
        }
        return -1;
    }
}

Related

  1. longToBytes(long aLong)
  2. longToBytes(long l)
  3. longToBytes(long l, int size)
  4. longToBytes(long x)
  5. longToBytes(long x, byte[] dest, int offset)
  6. longToFourBytesFlip(long l)
  7. longToHeight(long x)
  8. longToIPv4(Long ip)
  9. longToLE(long lVal)