-2

I have the code below and all I want is to create a random binary of fixed length (eg 4 bits). I want 4 bits to be used. I want it like that because after that I need to store it in a byte array (eg byte[][] myArray = new byte [2][0])

public String Random(){
    Random rg = new Random();
    int n = rg.nextInt();
    return Integer.toBinaryString(n);   
}
elli
  • 1,109
  • 1
  • 13
  • 20
  • 1
    A Java `Integer` is 32-bits. Use a `BitSet`. – Elliott Frisch May 19 '16 at 16:22
  • 2
    @elenaa A String is basically a Character Array, a Character depending on the encoding is 4 bytes or more per Character. If you used 4 bits, you will end up having padding when that 4 bits is converted to a byte, which may effect the outcome of your results. [Java Primitive Data Types](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) – Mr00Anderson May 19 '16 at 16:26

1 Answers1

2

If you want a string with 0/1, then its not a binary (since the String uses 2 bytes to represent each char)

public String generateRandom{
   String response = "";
   for(int i=0;i<4;i++){
      if(Math.random()>0.5{
         response +="1";
      } else {
         response += "0";
      }
   }
   return response;
}

Edit:

If you need bits, then you should use BitSet. However, the smallest bitset is 0 bits, the next smallest bitset size is 64 bits, and then multiples of that.
public Bitset generateRandom{
   BitSet response = new BitSet();
    for (int i = 0; i < 4; i++) {
        if (Math.random() > 0.5) {
            bitSet.flip(i);
        }
    }
   return response;
}
Bonatti
  • 2,778
  • 5
  • 23
  • 42
  • You did not specify if you want 4 bits used, or a String with 4 letters representing 0s and 1s. The letters will always use at least a byte (8 bits). – Bonatti May 19 '16 at 16:29
  • I want 4 bits used. Is this how I do it? – elli May 19 '16 at 16:32
  • 2
    No. I will edit the answer, and add a 4 bit response, but it wont be a String. You cannot have an array of chars (a string), to be less than the size of a char. You should edit your question, and show an example of what/why you need that. – Bonatti May 19 '16 at 16:36