1

I am trying to generate all of the possible binary combinations for two bytes ex.

00000000 00000001
00000000 00000010
00000000 00000011

I have the class that I'm working on but its clearly not working at all. I cant get the method to return the output as it is generated.

I got the code below to work properly, but only for calculation 1 byte. How would I change this to calculate all of the possible outcomes for 2 bytes?

package referenceCode;

public class BinaryGenerator {

private int val = 0; private int[] values = new int[]{0,1}; //This method converts the Binary Pattern output into a char[] so that it can be printed out to a file public int[] binaryPatternToString() { int numBits = 8; values[0] = 0; values[1] = 1; int[] returned = null; for (int i = 1; i < numBits; i++) { returned = binaryGenerator(i); for (int j = 1; j < numBits; j++) { } } return returned; } private int[] binaryGenerator(int iVal) { int[] moreValues = new int[values.length * 2]; int start = (int)Math.pow(2, iVal); for (int j = 0; j < values.length; j++) { moreValues[j * 2] = values[j] << 1; moreValues[j * 2 + 1] = values[j] << 1 | 1; } values = moreValues; for (int value : values) { System.out.println(Integer.toBinaryString(value)); } return moreValues; }}

Would it be a better idea or more efficient to make it a recursive method instead of a method with a for loop?

Matthewacon
  • 360
  • 3
  • 14
  • First, start over. Ask yourself "what result do I expect?". I see two answers: A list of integers with at most 2 bits set *or* a list of strings with the binary text (0's and 1's). So a `List` or `int[]` for option1 and a `List` or `String[]` for option2. Suggest going with lists, not arrays. Your code doesn't have a return type that can return what you want, so rest of code *cannot possibly* do the job. – Andreas Aug 26 '15 at 17:53
  • What do you expect to return from `binaryGenerator`? A `String` is just a single string. You can't return all 65536 combinations in a `String` (unless you concatenate them into one big string). Also, if you meant "two bits", which two bits? And if you meant "two bytes", please correct your question. – RealSkeptic Aug 26 '15 at 17:55
  • Question says "all of the possible binary combinations for two bits", but your example shows combinations with only *one* bit set. If one bit is ok, why not zero bits? --- Same if you meant "using only 2 right-most bits", but your question is *totally different* if that's what you meant. – Andreas Aug 26 '15 at 17:59
  • I'm quite sur OP means 2 bytes, not 2 bits. Héctor's solution here under will probably do the job. – Laurent S. Aug 26 '15 at 18:24

2 Answers2

4

As you may know all java Integers are based on binary numbers. So for 2 bytes, the maximum number is 2^16 = 65536. Simply loop through all numbers and get their binary values, zero-pad them if necessary and finally store them in a list. This will return all possible 2-byte binary numbers. For more bytes, simply increment the byte-variable.

Implementation:

int bytes = 2;
int nBits = bytes * 8;
int maxNumber = 1 << nBits; //this equals 2^nBits or in java: Math.pow(2,nbits)
ArrayList<String> binaries = new ArrayList<>();
for (int i = 0; i < maxNumber; i++) {
    String binary = Integer.toBinaryString(i);
    while (binary.length() != nBits) {
        binary = "0" + binary;
    }
    binaries.add(binary);
}
System.out.println(binaries);

The bytes and nBits variables are included simply for clarity.

You can also use a recursive method. Start with an empty String and recursively add a 0 or a 1 to the start of the string and continue until you've reached the number of bits you wanted:

public static ArrayList<String> getBinaries(int bits, String current) {
    ArrayList<String> binaries = new ArrayList<>();

    if (current.length() == bits) {
        binaries.add(current);
        return binaries;
    }

    //pad a 0 and 1 in front of current;
    binaries.addAll(getBinaries(bits, "0" + current));
    binaries.addAll(getBinaries(bits, "1" + current));

    return binaries;
}

You can call this function with: getBinaries(16,"") for 2 bytes.

Héctor van den Boorn
  • 1,139
  • 11
  • 25
  • 1
    `maxNumber` is `1< – Olivier Grégoire Aug 26 '15 at 18:26
  • @OlivierGrégoire: Of course you are right. Much quicker and cleaner. Thanks for the tip! – Héctor van den Boorn Aug 26 '15 at 18:29
  • Padding with 0's could also probably be improved using an answer to [this question](http://stackoverflow.com/questions/4469717/left-padding-a-string-with-zeros) – Laurent S. Aug 26 '15 at 18:30
  • 1
    Okay, now I understand how everything works. Before when I attempted this by myself I sort of flew in blindly hoping that whatever concoction of code that I theorized would work, but this seems much simpler than my initial code. Thanks for the help everybody! – Matthewacon Aug 26 '15 at 18:39
  • I just tested your recursive method, and if you put in a number larger than `20`, it crashes eclipse. I wonder what causes that? – Matthewacon Aug 26 '15 at 19:03
1

I took the liberty of writing my own version so you can see a simpler way to produce these numbers.

The hardest part here is incrementing the list of booleans. In general it's just like adding 1. You increment the one's slot, and if it was already a 1, you move on to the 10s slot, and so on. Otherwise, you just loop through all the posobilities, printing each one out.

import java.util.ArrayList;
import java.util.List;

public class Sandbox {

    // list of booleans to represent each bit
    private static List<Boolean> bytes = new ArrayList<>();

    public static void main(String[] args) {
        // initialize the list to all false
        for(int i = 0; i < 16; i++) {
            bytes.add(false);
        }

        // calculate the number of permutations
        int numPermutations = (int)Math.pow(2, 16);

        // print the first permutation
        print();

        // loop through all permutations
        for(int i = 0; i < numPermutations; i++) {
            // increment the 2 bytes
            increment();

            // print the current permutation
            print();
        }
    }

    /**
     * Prints out the current permutation
     */
    private static void print() {
        // loop through the bytes
        for(Boolean bool : bytes) {
            // print 1 or 0
            if(bool)
                System.out.print(1);
            else
                System.out.print(0);

        }

        // end the line
        System.out.println();
    }

    /**
     * Increment the bytes
     */
    private static void increment() {
        // set increment position to the end of the list
        int position = bytes.size() - 1;

        // loop through changing next digit if necessary, stopping
        // if the front of the list is reached.
        do {
            bytes.set(position, !bytes.get(position));
        } while(!bytes.get(position--) && position >= 0);
    }
}
Pherion
  • 155
  • 10