From 7e66e1b9191c70af81b9b95b21210579e8a5a9ea Mon Sep 17 00:00:00 2001 From: nguyennamthai Date: Mon, 11 Jun 2018 09:44:29 +0700 Subject: [PATCH] BAEL-1801 Add tests for unsigned arithmetic (#4442) --- .../java8/UnsignedArithmeticUnitTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java new file mode 100644 index 0000000000..e79c90b684 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.Assert.assertEquals; + +public class UnsignedArithmeticUnitTest { + @Test + public void whenDoublingALargeByteNumber_thenOverflow() { + byte b1 = 100; + byte b2 = (byte) (b1 << 1); + + assertEquals(-56, b2); + } + + @Test + public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + int signedComparison = Integer.compare(positive, negative); + assertEquals(1, signedComparison); + + int unsignedComparison = Integer.compareUnsigned(positive, negative); + assertEquals(-1, unsignedComparison); + + assertEquals(negative, positive + 1); + } + + @Test + public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + assertEquals(-1, negative / positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + + assertEquals(-1, negative % positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + } + + @Test + public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() { + Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648")); + assertThat(thrown).isInstanceOf(NumberFormatException.class); + + assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648")); + } + + @Test + public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() { + String signedString = Integer.toString(Integer.MIN_VALUE); + assertEquals("-2147483648", signedString); + + String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE); + assertEquals("2147483648", unsignedString); + } +}