UnsignedNumberUtil { public static byte[] toBytes(int ushortValue) { if (!isWithinUnsignedShort(ushortValue)) { throw new IllegalArgumentException(OUT_OF_RANGE_ERROR); } byte[] bytes = new byte[2]; bytes[1] = (byte) (0x00ff & (ushortValue)); bytes[0] = (byte) (0x00ff & (ushortValue >>> 8)); return bytes; } private  UnsignedNumberUtil(); static short getUnsignedByte(byte value); static int getUnsignedShort(ByteBuffer byteBuffer); static int getUnsignedShort(byte[] bytes); static long getUnsignedInt(ByteBuffer byteBuffer); static long getUnsignedInt(byte[] bytes); static BigInteger getUnsignedLong(ByteBuffer byteBuffer); static byte[] toBytes(int ushortValue); static byte[] toBytes(long uintValue); static byte[] toBytes(BigInteger unsignedLongValue); static boolean isWithinUnsignedByte(int value); static boolean isWithinUnsignedShort(int value); static boolean isWithinUnsignedInt(long value); static boolean isWithinUnsignedLong(BigInteger value); static final short UNSIGNED_BYTE_MAX; static final int UNSIGNED_SHORT_MAX; static final long UNSIGNED_INT_MAX; static final BigInteger UNSIGNED_LONG_MAX; }
@Test void toBytes_test1() { assertThrows(IllegalArgumentException.class, () -> UnsignedNumberUtil.toBytes((short) -1) ); }
@Test void toBytes_test2() { assertThrows(IllegalArgumentException.class, () -> UnsignedNumberUtil.toBytes(-1) ); }
@Test void toBytes_test3() { assertThrows(IllegalArgumentException.class, () -> UnsignedNumberUtil.toBytes((long) -1) ); }
@Test void toBytes_test4() { assertThrows(IllegalArgumentException.class, () -> UnsignedNumberUtil.toBytes(BigInteger.valueOf(-1)) ); }
@Test void toBytes_long_1_test1() { byte[] bytes = UnsignedNumberUtil.toBytes(0x00000001L); assertAll( () -> assertThat(bytes).hasSize(4), () -> assertThat(bytes).isEqualTo(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01}) ); }
@Test void toBytes_long_uint_max_test2() { byte[] bytes = UnsignedNumberUtil.toBytes(0xFFFFFFFFL); assertAll( () -> assertThat(bytes).hasSize(4), () -> assertThat(bytes).isEqualTo(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}) ); }
@Test void toBytes_ulong_max_test() { byte[] bytes = UnsignedNumberUtil.toBytes(UnsignedNumberUtil.UNSIGNED_LONG_MAX); assertThat(bytes).isEqualTo(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); }
@Test void toBytes_BigInteger_uint_max_test() { byte[] bytes = UnsignedNumberUtil.toBytes(BigInteger.valueOf(UnsignedNumberUtil.UNSIGNED_INT_MAX)); assertThat(bytes).isEqualTo(new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); }