如何将跳过最低有效位的BitSet的前20位随机化?

时间:2018-11-29 14:33:11

标签: java bitset

我正在尝试创建一个64位的BitSet,其中前20位是随机跳过LSB生成的-根据1的数目是奇数还是LSB,LSB必须设置为1或0。偶数(calculating个奇偶校验位)。

现在,我能够创建64位,其中LSB设置为1,因为1s(0)的数量为偶数。我要实现的是随机设置前20位(我猜是MSB)。

BitSet temp = new BitSet();

        for (int i = 0; i < temp.size() / 8; i++) {
            int msb = i * 8;
            BitSet group = temp.get(msb, msb + 8);
            temp.set(msb + 7, group.cardinality() % 2 == 0);
        }

        StringBuilder sb = new StringBuilder();
        for( int i = 0; i < temp.length();  i++ )
        {
            sb.append( temp.get( i ) == true ? 1: 0 );
        }

        System.out.println("Bitset " + sb);

这给出了输出:

Bitset 0000000100000001000000010000000100000001000000010000000100000001

我希望它是这样的:

xxxxxxxp xxxxxxxp xxxxxx0p 0000000p 0000000p 0000000p 0000000p 0000000p

x是随机设置的位(0或1),而p是奇偶校验位。

1 个答案:

答案 0 :(得分:1)

我想唯一的一件事,就是您所缺少的是:

import java.util.Random; // see javadoc!

  Random rand = new Random(/*seed to re-produce sequence*/);
  ...
  for (int i = 0; i < temp.size() / 8; i++) {
        int msb = i * 8;
        // this can be done "maybe nicer", but in general -
        // set the next 7 bits (of temp up to 19th) randomly:
        for (int j = msb; j < msb + 7 && j < 20; j++) {
            temp.set(j, rand.nextBoolean());
        }

        //this should work as intended..
        BitSet group = temp.get(msb, msb + 8);
        temp.set(msb + 7, group.cardinality() % 2 == 0);
        ...
  }

您可以(可能)使用以下方法避免循环(1..7):

int randBits = rand.next(7);

...以及:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
        (byte)(value >>> 24),
        (byte)(value >>> 16),
        (byte)(value >>> 8),
        (byte)value};
}

要做:

BitSet group = BitSet.valueOf(intToByteArray(randBits));

...但是您必须mergre/concatenate the single groups...