ByteUtil { public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { if (b == null) return null; byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; int length = Math.min(biBytes.length, numBytes); System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; }  static byte[] appendByte(byte[] bytes, byte b); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static byte[] bigIntegerToBytes(BigInteger value); static int matchingNibbleLength(byte[] a, byte[] b); static byte[] longToBytes(long val); static String toHexString(byte[] data); static byte[] calcPacketLength(byte[] msg); static int byteArrayToInt(byte[] b); static String nibblesToPrettyString(byte[] nibbles); static String oneByteToHexString(byte value); static int numBytes(String val); static byte[] encodeValFor32Bits(Object arg); static byte[] encodeDataList(Object... args); static byte[] stripLeadingZeroes(byte[] data); static boolean increment(byte[] bytes); static byte[] copyToArray(BigInteger value); static final byte[] EMPTY_BYTE_ARRAY; }
@Test public void testBigIntegerToBytes() { byte[] expecteds = new byte[]{(byte) 0xff, (byte) 0xec, 0x78}; BigInteger b = BigInteger.valueOf(16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); }
@Test public void testBigIntegerToBytesNegative() { byte[] expecteds = new byte[]{(byte) 0xff, 0x0, 0x13, (byte) 0x88}; BigInteger b = BigInteger.valueOf(-16772216); byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); }
@Test public void testBigIntegerToBytesZero() { byte[] expecteds = new byte[]{0x00}; BigInteger b = BigInteger.ZERO; byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); }