/** * This method is similar to {@link #widenNumber}, but only integral types <i>that are negative</i> are widened. * * @param number an integral number to treat as unsigned. * @return an equivalent value that Java will interpret as non-negative. */ public static Number widenNumberIfNegative(Number number) { if (number instanceof Byte && number.byteValue() < 0) { return unsignedByteToShort(number.byteValue()); } else if (number instanceof Short && number.shortValue() < 0) { return unsignedShortToInt(number.shortValue()); } else if (number instanceof Integer && number.intValue() < 0) { return unsignedIntToLong(number.intValue()); } else if (number instanceof Long && number.longValue() < 0) { return unsignedLongToBigInt(number.longValue()); } return number; }
return unsignedIntToLong(number.intValue()); } else if (number instanceof Long) { return unsignedLongToBigInt(number.longValue()); } else { return number;
@Test public void testUnsignedLongToBigInt() { Assert.assertEquals("The long round-trips as expected.", Long.MAX_VALUE, DataType.unsignedLongToBigInt(Long.MAX_VALUE).longValueExact()); BigInteger overflowAsBigInt = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); Assert.assertEquals(new BigInteger("9223372036854775808"), overflowAsBigInt); long overflowAsLong = overflowAsBigInt.longValue(); Assert.assertEquals(-9223372036854775808L, overflowAsLong); Assert.assertEquals("Interpret signed long as unsigned long", overflowAsBigInt, DataType.unsignedLongToBigInt(overflowAsLong)); }