Skip to content

Commit 7e66e1b

Browse files
nguyennamthaiKevinGilmore
authored andcommitted
BAEL-1801 Add tests for unsigned arithmetic (eugenp#4442)
1 parent ea37ada commit 7e66e1b

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.java8;
2+
3+
import org.junit.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
import static org.assertj.core.api.Assertions.catchThrowable;
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class UnsignedArithmeticUnitTest {
10+
@Test
11+
public void whenDoublingALargeByteNumber_thenOverflow() {
12+
byte b1 = 100;
13+
byte b2 = (byte) (b1 << 1);
14+
15+
assertEquals(-56, b2);
16+
}
17+
18+
@Test
19+
public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() {
20+
int positive = Integer.MAX_VALUE;
21+
int negative = Integer.MIN_VALUE;
22+
23+
int signedComparison = Integer.compare(positive, negative);
24+
assertEquals(1, signedComparison);
25+
26+
int unsignedComparison = Integer.compareUnsigned(positive, negative);
27+
assertEquals(-1, unsignedComparison);
28+
29+
assertEquals(negative, positive + 1);
30+
}
31+
32+
@Test
33+
public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() {
34+
int positive = Integer.MAX_VALUE;
35+
int negative = Integer.MIN_VALUE;
36+
37+
assertEquals(-1, negative / positive);
38+
assertEquals(1, Integer.divideUnsigned(negative, positive));
39+
40+
assertEquals(-1, negative % positive);
41+
assertEquals(1, Integer.divideUnsigned(negative, positive));
42+
}
43+
44+
@Test
45+
public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() {
46+
Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648"));
47+
assertThat(thrown).isInstanceOf(NumberFormatException.class);
48+
49+
assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648"));
50+
}
51+
52+
@Test
53+
public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() {
54+
String signedString = Integer.toString(Integer.MIN_VALUE);
55+
assertEquals("-2147483648", signedString);
56+
57+
String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE);
58+
assertEquals("2147483648", unsignedString);
59+
}
60+
}

0 commit comments

Comments
 (0)