Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使随机位存储在布尔数组中_Java_Arrays_Random_Boolean_Bits - Fatal编程技术网

Java 使随机位存储在布尔数组中

Java 使随机位存储在布尔数组中,java,arrays,random,boolean,bits,Java,Arrays,Random,Boolean,Bits,我正在寻找一种将随机比特集存储到数组中的方法。下面的代码并不完整,但我只是想帮助您理解如何将一组位随机化 public static boolean[] makeRandomBits(int size) { BitSet[] bitArray = new BitSet[size]; for(int i=0; i<size; i++){ bitArray[i].set(/*Right here is where my confusion is*/);

我正在寻找一种将随机比特集存储到数组中的方法。下面的代码并不完整,但我只是想帮助您理解如何将一组位随机化

public static boolean[] makeRandomBits(int size) {
    BitSet[] bitArray = new BitSet[size];
    for(int i=0; i<size; i++){
        bitArray[i].set(/*Right here is where my confusion is*/);
    }

    /*other stuff below*/
}
我希望输出类似于:01101001

类java.math.biginger提供了一个可创建给定位长度的随机biginger的类,您可以在位级别对其进行操作

Random random = new Random();
boolean[] arr = new boolean[size];
for (int i = 0; i < size; ++i) {
   arr[i] = random.nextBoolean();
}
return arr;
Random r = new Random();
int numBits = 32;

BigInteger bi = new BigInteger(numBits,r); 
如果需要将其设置为位集:


有关更多信息,请查看和javadocs。

如果我希望代码返回类似01101001或11010101的值,那么使用此方法是否可行?对不起,我认为我在最初的问题中没有说清楚。嗯。。。那就更容易了。新的IntegrarDomain.NextInSomeMax.ToBinarystring我不确定我是否了解你。本例中的变量someMax是否为比特数,即如果someMax为7,它将创建从11111111到00000000的随机比特?在本例中,someMax将为2^7
BitSet bs = BitSet.valueOf(bi.toByteArray());