简体   繁体   中英

Java: How to output all possible binary combinations (256 different sequences)?

I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.

Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.

The output should look like this:

00000000

00000001

00000010

00000011

00000100

...

11111110

11111111

public static void outputBinary(){

int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];

    for (int i = 0; i < 2; i++){

    for (int j = 0; j < 2; j++){

    for (int k = 0; k < 2; k++){

    for (int l = 0; l < 2; l++){

    for (int m = 0; m < 2; m++){

    for (int n = 0; n < 2; n++){

    for (int o = 0; o < 2; o++){

    for (int p = 0; p < 2; p++){

        System.out.print(num[i][j][k][l][m][n][o][p]);

    } }}}}}}}

}

Thanks for looking.

No need for the array. Here is a slight modification to your code that will output all the permutations.

for (int i = 0; i < 2; i++){
  for (int j = 0; j < 2; j++){
    for (int k = 0; k < 2; k++){
      for (int l = 0; l < 2; l++){
        for (int m = 0; m < 2; m++){
          for (int n = 0; n < 2; n++){
            for (int o = 0; o < 2; o++){
              for (int p = 0; p < 2; p++){
                System.out.println("" + i + j + k + l + m + n + o + p);
              }
            }
          }
        }
      }
    }
  }
}

Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.

for (int i=0; i<256; i++) {
    System.out.println(Integer.toBinaryString(i));
}

只需打印for变量 ( i...p ) 而不访问这个晦涩的空数组。

Well, if it's OK to use some built-in classes, you can do this in the following way:

for (int i=0; i<256; i++){
    System.out.println(Integer.toBinaryString(i));
}

And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask ):

for (int i=0;i<256;i++){
    int mask = 256;
    while (mask > 0){
        if ((mask & i) == 0){
            System.out.print("0");
        } else {
            System.out.print("1");
        }
        mask = mask >> 1;
    }
    System.out.println();
}

Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:

public static void printBin()
{
    for (int i = 0; i < 256; i++) {
        int binary = decToBin(i, "");
        // pad to give length of 8
        System.out.println(String.format("%08d", binary));
    }
}

public static int decToBin(int dec, String bin)
{
    int quot = dec / 2;
    int remainder = dec % 2;
    if (quot == 0)
        return Integer.parseInt("" + remainder + bin);
    return decToBin(quot, "" + remainder + bin);
}

Heres another way of generating all the values using bit operations

public static void main(String[] args) {
    int numBits = 8;

    int val = 0;
    int[] values = new int[]{0,1};
    values[0] = 0;
    values[1] = 1;

    for (int i = 1; i < numBits; i++) {
        int[] moreValues = new int[values.length * 2];
        int start = (int)Math.pow(2, i);
        for (int j = 0; j < values.length; j++) {
            moreValues[j * 2] = values[j] << 1;
            moreValues[j * 2 + 1] = values[j] << 1 | 1;
        }
        values = moreValues;
    }

    //print the values
    for (int value: values) {
        System.out.println(Integer.toBinaryString(value));
    }

}

And another way, using bit operations and recursion

private static void generateNumbers(int number, int numBits, int currentBit) {
    if (numBits == currentBit) {
        Integer.toBinaryString(number);
        return;
    }
    currentBit++;

    generateNumbers(number << 1, numBits, currentBit);
    generateNumbers(number << 1 | 1, numBits, currentBit);

}

public static void generateNumbers(int numBits) {
    generateNumbers(0, 8, 1);
    generateNumbers(1, 8, 1);
}

public static void main(String[] args) {
    generateNumbers(8);

}
package org.cross.topology;

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {

        //System.out.println("sushil");
        int digits=3;//Provide number of digits for which you want combinations of 0 and 1
        int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
        String current_char="0";
        int startindex=0,lastindex;

        ArrayList<String> al=new ArrayList<String>(combinations);
        for(int k=0;k<combinations;k++)
        {
            al.add("");
        }

        for(int i=1;i<=digits;i++)
        {
            noof0and1=noof0and1/2;
            while(temp!=combinations)
            {
                temp=temp+noof0and1;
                secondloopcounter++;
            }
            lastindex=noof0and1;
            startindex=0;
            for(int s=0;s<secondloopcounter;s++)
            {
                for(int j=startindex;j<lastindex;j++)
                {
                    String temps=al.get(j)+current_char;
                    al.remove(j);
                    al.add(j, temps);
                }

                    if(current_char.equals("0"))
                    {
                        current_char="1";
                    }
                    else
                    {
                        current_char="0";
                    }
              startindex=lastindex;
              lastindex=lastindex+noof0and1;
            }

            temp=0;
            secondloopcounter=0;
        }

        for(int l=0;l<al.size();l++)
        {
            System.out.println(al.get(l));
        }
    }

}

Below is the solution using Recursion as an approach in java

public class NumberOfBinaryPatterns {

    static int[] bitArray = new int[]{0,1};

    public static void main(String args[])
    {   
        System.out.println("Below are the patterns\n");

        int numberOfBits=4;  // It can be any value based on the requirement, In this case we can put this as 8

        drawBinaryPattern(numberOfBits,"");
    }

    private static void drawBinaryPattern(int n,String seed)
    {
        if(n==0){
            System.out.println(seed);
            return;
        }   
        for(int j=0;j<bitArray.length;j++)
        {
            String temp = seed+bitArray[j];
            drawBinaryPattern(n-1,temp);
        }
    }
}

Do in php , very easy Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.

    for($c=1;$c<=pow(2,8);$c++)
    {
      $bin_str=base_convert($c,10,2);   //converting combination number into binary string
      $len_str=strlen($bin_str);        // Length of string obtained
      for($i=1;$i<=8-$len_str;$i++)
        $bin_str="0".$bin_str;      // adding as many 0 as required to complete in byte format

      echo "<br>".$bin_str;         //Displaying binary values in byte structure

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM