How to create BigInteger of 256 bits with all bits set

核能气质少年 提交于 2019-12-19 10:12:19

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/48993728/how-to-create-biginteger-of-256-bits-with-all-bits-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!