Here you can find the source of unsignedLongToByteArray(final long value)
public final static byte[] unsignedLongToByteArray(final long value)
//package com.java2s; /*/*from w w w .j a v a 2 s . c om*/ * Part of the CCNx Java Library. * * Copyright (C) 2008-2012 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ public class Main { /** * Convert a long value to a Big Endian byte array. Assume * the long is not signed. * * This should be the equivalent of: * byte [] b = BigInteger.valueOf(toBinaryTimeAsLong()).toByteArray(); if( 0 == b[0] && b.length > 1 ) { byte [] bb = new byte[b.length - 1]; System.arraycopy(b, 1, bb, 0, bb.length); b = bb; } */ private final static byte[] _byte0 = { 0 }; public final static byte[] unsignedLongToByteArray(final long value) { if (0 == value) return _byte0; if (0 <= value && value <= 0x00FF) { byte[] bb = new byte[1]; bb[0] = (byte) (value & 0x00FF); return bb; } byte[] out = null; int offset = -1; for (int i = 7; i >= 0; --i) { byte b = (byte) ((value >> (i * 8)) & 0xFF); if (out == null && b != 0) { out = new byte[i + 1]; offset = i; } if (out != null) out[offset - i] = b; } return out; } /** * Like unsignedLongToByteArray, except we specify what the first byte should be, so the * array is 1 byte longer than normal. This is used by things that need a CommandMarker. * * If the value is 0, then the array will be 1 byte with only @fistByte. The 0x00 byte * will not be included. */ public final static byte[] unsignedLongToByteArray(final long value, final byte firstByte) { // A little bit of unwinding for common cases. // These hit a lot of the SegmentationProfile cases if (0 == value) { byte[] bb = new byte[1]; bb[0] = firstByte; return bb; } if (0 <= value && value <= 0x00FF) { byte[] bb = new byte[2]; bb[0] = firstByte; bb[1] = (byte) (value & 0x00FF); return bb; } if (0 <= value && value <= 0x0000FFFFL) { byte[] bb = new byte[3]; bb[0] = firstByte; bb[1] = (byte) ((value >>> 8) & 0x00FF); bb[2] = (byte) (value & 0x00FF); return bb; } byte[] out = null; int offset = -1; for (int i = 7; i >= 0; --i) { byte b = (byte) ((value >> (i * 8)) & 0xFF); if (out == null && b != 0) { out = new byte[i + 2]; offset = i; } if (out != null) out[offset - i + 1] = b; } out[0] = firstByte; return out; } }