Skip to content

Commit 2c64f64

Browse files
Saber-kMateusz Szablak
and
Mateusz Szablak
authored
BAEL-4920 - How BigInteger works (eugenp#11016)
Co-authored-by: Mateusz Szablak <[email protected]>
1 parent 6955db5 commit 2c64f64

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.biginteger;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.math.BigInteger;
6+
import java.nio.ByteBuffer;
7+
8+
import static org.junit.jupiter.api.Assertions.assertEquals;
9+
import static org.junit.jupiter.api.Assertions.assertTrue;
10+
11+
public class BigIntegerUnitTest {
12+
13+
@Test
14+
void givenPositiveAndNegativeAndZeroBigInteger_whenGetSigNumValue_shouldReturnOneAndMinusOneAndZero() {
15+
assertEquals(1, BigInteger.TEN.signum());
16+
assertEquals(-1, BigInteger.TEN.negate().signum());
17+
assertEquals(0, BigInteger.ZERO.signum());
18+
}
19+
20+
@Test
21+
void givenByteArrays_whenCreateBigInteger_shouldTranslateToTwosComplementBinary() {
22+
assertEquals(new BigInteger("1"), new BigInteger(new byte[]{0b1}));
23+
assertEquals(new BigInteger("2"), new BigInteger(new byte[]{0b10}));
24+
assertEquals(new BigInteger("4"), new BigInteger(new byte[]{0b100}));
25+
}
26+
27+
@Test
28+
void givenSingleByte_whenCreateBigIntegerAndDifferentSigNum_thenOppositeValues() {
29+
byte[] bytes = { (byte) -128 }; // 0b1000_0000
30+
31+
BigInteger positive = new BigInteger(1, bytes);
32+
BigInteger negative = new BigInteger(-1, bytes);
33+
34+
assertEquals(new BigInteger("128"), positive);
35+
assertEquals("10000000", positive.toString(2));
36+
37+
assertEquals(new BigInteger("-128"), negative);
38+
assertEquals("-10000000", negative.toString(2));
39+
}
40+
41+
@Test
42+
void givenZeroBigInteger_whenCheckMagnitude_thenIsEmpty() {
43+
assertEquals(0, BigInteger.ZERO.bitCount());
44+
assertEquals(BigInteger.ZERO, new BigInteger(0, new byte[]{}));
45+
}
46+
47+
@Test
48+
void given63rdBitSet_whenCreateBigInteger_thenIsLargerThanLongByOne() {
49+
// first
50+
BigInteger bi1 = BigInteger.ZERO.setBit(63);
51+
String str1 = bi1.toString(2);
52+
53+
// second
54+
byte[] bytes = ByteBuffer.allocate(Long.BYTES).putLong(Long.MIN_VALUE).array();
55+
BigInteger bi2 = new BigInteger(1, bytes);
56+
String str2 = bi2.toString(2);
57+
58+
largerThanLongAssertionSet(bi1, str1);
59+
60+
assertEquals(bi1, bi2);
61+
62+
largerThanLongAssertionSet(bi2, str2);
63+
64+
}
65+
66+
private static void largerThanLongAssertionSet(BigInteger bi, String str)
67+
{
68+
assertEquals(64, bi.bitLength());
69+
assertEquals(1, bi.signum());
70+
assertEquals("9223372036854775808", bi.toString());
71+
assertEquals(BigInteger.ONE, bi.subtract(BigInteger.valueOf(Long.MAX_VALUE)));
72+
73+
assertEquals(64, str.length());
74+
assertTrue(str.matches("^10{63}$")); // 1000 0000
75+
}
76+
}

0 commit comments

Comments
 (0)