Reputation: 367
How can I create a BigInteger with 256 bits that are all set ? I've already tried the following:
BigInteger.valueOf(0xFFFFFFFFFFFFFFFFL)
But it doesn't give me the desired result:
int bitCount = b.bitCount();// 0
int bitLength = b.bitLength();// 0
What I basically need is a number containing 256 bits which are all set.
Tnx!
Upvotes: 3
Views: 3692
Reputation: 43798
Try this:
BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE)
It calculates first 2^256, which is in binary a one followed by 256 zeroes, and then subtracts one which leaves just 256 ones.
Upvotes: 11
Reputation: 159260
BigInteger with 256 1-bits:
byte[] b = new byte[256 / 8 + 1]; // 256 bits + 1 byte
Arrays.fill(b, (byte) 0xFF); // with all 1's
b[0] = 0; // except first 8 bits 0's, so value is positive
BigInteger bi = new BigInteger(b);
System.out.println(bi);
System.out.println("bitCount = " + bi.bitCount());
System.out.println("bitLength = " + bi.bitLength());
Output
115792089237316195423570985008687907853269984665640564039457584007913129639935
bitCount = 256
bitLength = 256
A bit more cumbersome than answer by @Henry, but likely faster, though that probably doesn't matter.
Upvotes: 0