1

I am trying to create a BitSet of 64 bits where the first 20 bits are generated randomly skipping the LSB - The LSB has to either be set to 1 or 0 depending on if the number of 1s are odd or even (calculating the parity bits).

Right now, I am able to create 64 bits where the LSB is set to 1 as the number of 1s (0) are even. What I want to achieve is to randomly set the first 20 bits (the MSB I guess).

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);

This gives the output:

Bitset 0000000100000001000000010000000100000001000000010000000100000001

Where I want it to be something like:

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

Where x is the randomly set bit (either 0 or 1) and p is the parity bit.

Bab
  • 433
  • 5
  • 12
  • `new Bitset()` creates a BitSet with no bits set. I don’t see any code that sets your `x` bits. – VGR Nov 29 '18 at 16:02
  • I know, that is what I am asking for. I was thinking about having an if statement, which checks if the group of 8 bits is the third or less, then I would call Random:nextBoolean(). However, I am not how to keep track of that while keeping the right most bit as either 0 or 1 depending on if the number of 1s are even or odd. – Bab Nov 29 '18 at 16:14
  • `== true` is (always) redundant -> `temp.get(i)? '1' : '0'` – xerx593 Feb 06 '19 at 11:26

1 Answers1

1

I think the only thing, what you are missing is:

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);
        ...
  }

You can (probably) avoid the loop (1..7) by using:

int randBits = rand.next(7);

...and with:

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

do:

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

...but you would have to mergre/concatenate the single groups...

xerx593
  • 12,237
  • 5
  • 33
  • 64