Krishnendu Rarhi
Krishnendu Rarhi

Reputation: 25

Binary Random Number

I have a situation where I need t generate 16 unique random sequence of 50- bit binary numbers. And then store it in a 4x4 matrix into a file.

I have done it in this manner

import java.util.Random; 
public class BitGenerator{ 
public static void main(String[] args) { 
 String bits = ""; 
 Random r = new Random(); 
 for(int j=0; j<15; j++){ 
   for(int i=0; i<50; i++){ 
     int x = 0; 
     if(r.nextBoolean()) x=1; 
     bits += x; 
   }
  }
 System.out.println(bits); 
} 
}

but when I am running this program, "java BitGenerator > Random.doc", its showing all the characters in one go. Please help.

Upvotes: 0

Views: 1167

Answers (2)

Linus
Linus

Reputation: 1518

Instead of using booleans you can use bitwise operations (see Jack's answer) to extract a random binary value and insert it into a string matrix. Here is a live example.

final Random r = new Random();
String matrix[][] = new String[4][4];

for (int i = 0; i < 4; ++i)
{
    for (int j = 0; j < 4; ++j)
    {
        long value = r.nextLong() >>> -50;
        value |= 1L << 50;
        matrix[i][j] = Long.toBinaryString(value).substring(1);
    }
}

Upvotes: 0

Jack
Jack

Reputation: 133619

Can't you just generate a 64 bit random number and then mask it to get only the least significative 50 bits? Something like:

final Random r = new Random();

for (int i = 0; i < 16; ++i)
{
  long value = r.nextLong() & 0x3FFFFFFFFFFFFL;
  String stringValue = Long.toBinaryString(value);
  // pad stringValues with 0s if length < 50
  // or set to 1 the 51th bit and then trim first character

  // output number on file
}

To force the string to be 50 chars you can use a sort of hack, set 51th bit and then discard first character, something like:

value |= 1L << 50;
String stringValue = Long.toBinaryString(value).substring(1);

Upvotes: 1

Related Questions